这可能是 this answered question的重复,但我似乎无法得到相同的结果.希望在这里有一些指导.
JSEncrypt(客户端)
let encrypt = new Encrypt.JSEncrypt();
encrypt.setPublicKey(this.publicKey); // retrieved from server
encrypt.encrypt(password);
BouncyCastle(服务器) – RSA密钥生成
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair pair = generator.generateKeyPair();
PublicKey pubKey = pair.getPublic();
PrivateKey privKey = pair.getPrivate();
// returned to client
String publicKeyStr = new String(Base64.encodeBase64(pubKey.getEncoded()));
String privateKeyStr = new String(Base64.encodeBase64(privKey.getEncoded()));
BouncyCastle(服务器) – 解密
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// org.apache.commons.codec.binary.Hex
byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));
decrypted = new String(cipherText, BaseConstant.ENC_UTF8);
错误
org.apache.commons.codec.DecoderException: Illegal hexadecimal character I at index 0
at org.apache.commons.codec.binary.Hex.toDigit(Hex.java:178)
at org.apache.commons.codec.binary.Hex.decodeHex(Hex.java:89)
我注意到的一件事是JSEncrypt的加密文本长度为172,而服务器端的加密产生256.
回答的问题提到使用RSA / None / PKCS1Padding,我已经设置了.我还能错过什么?
最佳答案 Hex.decodeHex()方法中发生错误,这意味着您的数据不是十六进制编码的字符串.
JSEncrypt.encrypt()方法返回Base64中的加密数据(而不是Hex字符串).要解密它,您必须从base64格式解码它.
所以代替:
byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));
做这个:
byte[] cipherText = cipher.doFinal(Base64.decodeBase64(encrypted.toCharArray()));