简体   繁体   English

Aes javascript加密 - java解密

[英]Aes javascript encrypt - java decrypt

I'm trying to encrypt a message in javascript (using crypto-js library) and to decrypt it in java. 我正在尝试使用javascript(使用crypto-js库)加密消息并在java中解密它。

This is the javascript code: 这是javascript代码:

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: 这是java代码:

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 但是当我尝试在Java中解密时抛出此异常:javax.crypto.BadPaddingException:给定最终块未正确填充

password: 6h2faBePVxpgyFSN iv: NKOzRKrmEMKs1kE4 data to encrypt: "{token: cMGOIrYlJm9lPhPW}" 密码:6h2faBePVxpgyFSN iv:要加密的NKOzRKrmEMKs1kE4数据:“{token:cMGOIrYlJm9lPhPW}”

Any help? 有帮助吗?

Thanks in advance 提前致谢

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). 我可能错了,但我认为在这种情况下BadPaddingException意味着你没有正确的密钥来成功执行解密。异常本质上意味着密钥太短或太长(我认为)。

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. 上面的代码之类的东西可能会起作用,因为仅在未捕获BadPaddingException时达到System.out,这可以在尝试可能的解密密钥时在循环中使用,例如,如果您尝试计算所有可能的密钥解密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM