如何模拟Javascript crypto AES

我在网页中有以下Javascript代码:

  var decrypt = function (text, password){
    var decipher = crypto.createDecipher('aes-256-cbc',password);
    var dec = decipher.update(text,'hex','utf8');
    dec += decipher.final('utf8');
    return dec;
  }

,并且我试图使用Java重现它,使用以下内容:

static MessageDigest MD5 = null;

static {
    try {
        MD5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}


public static String decrypt(String cipherText, String password)
        throws GeneralSecurityException, UnsupportedEncodingException {
    byte[] passwordBytes = hexStringToByteArray(password);
    byte[] keyBytes = MD5.digest(passwordBytes);
    byte[] keyAndPassword = new byte[keyBytes.length + passwordBytes.length];
    System.arraycopy(keyBytes, 0, keyAndPassword, 0, keyBytes.length);
    System.arraycopy(passwordBytes, 0, keyAndPassword, keyBytes.length, passwordBytes.length);
    byte[] ivBytes = MD5.digest(keyAndPassword);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    byte[] encrypted = hexStringToByteArray(cipherText);
    Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
    aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
    byte[] decryptedData = aesCBC.doFinal(encrypted);
    return new String(decryptedData, StandardCharsets.UTF_8);
}

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}

从以下部分中分块:

  • 使用Node.js Crypto模块加密并使用Java解密(在Android应用程序中)
  • CryptoJS AES加密和Java AES解密
  • ,但我得到了“javax.crypto.BadPaddingException:给定的最终块未正确填充”,在JS函数正确解码的参数上。

    注意给定的最终块没有被正确填充并不能回答这个问题 - 因为很明显,这是一个填充问题,但解决方案是复制JS加密lib所做的任何事情,但没有详细记录。

    链接地址: http://www.djcxy.com/p/49163.html

    上一篇: How to emulate Javascript crypto AES

    下一篇: Encrypt in java and Decrypt in C# For AES 256 bit