JSEncrypt encrypt but java cannot decrypt-BadPaddingException

720 views Asked by At

I'm trying encrypt data with JSEncrypt (v 2.3.1) then server decrypt data (Java). Most of time it works, but sometime backend throw BadPaddingException.

I found on stack it may be duplicated with this question: JSEncrypt(js) encrypt, but python cannot decrypt but seem it not same exception.

I googled and I found the issue: JSEncrypt#encrypt creates sporadically invalid ciphertexts. But when I tried reproduced issue follow the github link, backend code still decrypt data. Could anyone give some suggestions ?

JS code:

function encryptInput(input,key){
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    var encrypted = encrypt.encrypt(input);
    return encrypted;  
}

Java code:

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 "";
    }
}

Exception:

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)
0

There are 0 answers