我正在尝试使用 JSEncrypt (v 2.3.1) 加密数据,然后服务器解密数据 (Java)。大多数时候它可以工作,但有时后端会抛出 BadPaddingException。
我在堆栈上发现它可能与这个问题重复: JSEncrypt(js) encrypt, but python cannot decrypt但似乎不是同一个异常。
我用谷歌搜索,发现了问题:JSEncrypt#encrypt 创建偶尔无效的密文。但是当我尝试按照 github 链接复制问题时,后端代码仍然解密数据。有人可以提出一些建议吗?
JS代码:
function encryptInput(input,key){
var encrypt = new JSEncrypt();
encrypt.setPublicKey(key);
var encrypted = encrypt.encrypt(input);
return encrypted;
}
Java代码:
public String decryptWeb(String cipherText, String privateKey){
try{
// Remove the first and last lines
privateKey = privateKey.replace("-----BEGIN PRIVATE KEY-----", "");
privateKey = privateKey.replace("-----END PRIVATE KEY-----", "");
// Base64 decode data
byte[] encoded = Base64.decodeBase64(privateKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), "UTF-8"); // exception throw here
}catch(Exception ex){
LOG.error("decrypt",ex);
return "";
}
}
例外:
decrypt - decrypt
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at com.util.Decryptor.decrypt(Decryptor.java:161)