使用RSA加解密时注意Cipher.getInstance(String var0,Provider var1)提供的Provider是否正确

前言

项目中,APP(IOS和Android)与后台(JAVA)对接时,某个接口的数据经过IOS端的RSA加密后,后台总是解密出来的不对。本文不讨论RSA算法细节,只记录使用中注意事项。

错误来源

我们的RSA使用规则是后台生成密钥对,对外提供公钥的指数(Exponent)和模数(Modulus),然后接口调用者需要根据这两个参数去生成公钥,然后使用公钥对数据加密后传输给后台,后台再解密。

// 生成密钥对
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new BouncyCastleProvider());
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();

// 省略...saveKeyPair,保存生成的公钥、私钥

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

// 将公钥中的指数(Exponent)和模数(Modulus)转为某种编码/加密格式提供给前端APP
String modulus = new String(xxxMethod(publicKey.getModulus().toByteArray()));
String exponent = new String(xxxMethod(publicKey.getPublicExponent().toByteArray()));

ycyin大约 3 分钟安全&设计RSABouncyCastleProvider