Aes javascript encrypt - java decrypt

ⅰ亾dé卋堺 提交于 2019-12-05 06:49:29

问题


I'm trying to encrypt a message in javascript (using crypto-js library) and to decrypt it in java.

This is the javascript code:

var key = CryptoJS.enc.Utf8.parse(aesPassword);
var ive  = CryptoJS.enc.Utf8.parse(aesIv);
var encryptedData = CryptoJS.AES.encrypt(dataToEncrypt, key, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: ive});

And this is the java code:

final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final SecretKeySpec key = new SecretKeySpec(aesPassword().getBytes("UTF-8"), "AES");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(aesIv().getBytes("UTF-8")));
        byte[] decrypted = cipher.doFinal(DatatypeConverter.parseBase64Binary(message));

But when I try to decrypt in Java this exception is thrown: javax.crypto.BadPaddingException: Given final block not properly padded

password: 6h2faBePVxpgyFSN iv: NKOzRKrmEMKs1kE4 data to encrypt: "{token: cMGOIrYlJm9lPhPW}"

Any help?

Thanks in advance


回答1:


I may be wrong, but I think BadPaddingException in this case means that you don't possess the correct key to successfully perform the decryption.The exception essentially means that the key is either too short or too long (I think).

Try{
    String decrypted = aes.decrypt(...);
    System.out.println(decryted);
}catch(Exception e){

}

Something like the code above may work, as System.out is only reached when the BadPaddingException isn't caught, this could be used in a loop when trying possible keys for decryption, for example, if you were trying to calculate all possible keys for the decryption.



来源:https://stackoverflow.com/questions/43518391/aes-javascript-encrypt-java-decrypt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!