在JavaScript中加密并在Java中解密 - 不起作用



iam加密在JavaScript中,在Java中解密,但要低于错误:

在Java中丢下错误:java.lang.exception:给定最终块未正确填充

下面是我的Java脚本代码:

var key =CryptoJS.enc.Utf8.parse("0123456789012345");
var ive  = CryptoJS.enc.Utf8.parse("0123456789012345");
var encrypted = CryptoJS.AES.encrypt(password, key, {iv: ive});
console.log('encrypted msg = ' + encrypted.toString());

var afterEncryptionText = encrypted.toString();
console.log("encrypted password: " + afterEncryptionText);

Java代码:

public String decrypt(String cipherText) throws Exception {
    try {
        String encryptionKey = "0123456789012345";
        String ive = "0123456789012345";
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        final SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ive.getBytes("UTF-8")));
        return new String(cipher.doFinal(cipherText.getBytes("UTF-8")),"UTF-8");
    } 
    catch(Exception e){
        throw new Exception(e.getMessage());
    }
}

我发现,加密数据作为字符串的表示倾向于导致有损的转换。当我尝试将加密字节直接转换为字符串时,通常会丢失字节或对某些控制字符的字节。

我建议直接传输字节后接种。如果这是不可能的,或者您不舒服,我建议将加密字节代表一个数字(例如base-16或base-64),传输包含数字的字符串,在接收方中解析数字,通过执行表示过程的倒数并解密这些字节,从该数字中获取字节。例如,可以使用BigInteger类,也可以编写自己的base-16编码器。

最新更新