【发布时间】:2018-07-05 15:26:41
【问题描述】:
我在 NODEJS 中加密文本并尝试在 Java 中解密但出现错误。 我的nodejs代码:
var crypto = require('crypto')
, key = 'mykey@91'
, plaintext = 'SS18617710213463'
, cipher = crypto.createCipher('aes-128-ecb', key)
, decipher = crypto.createDecipher('aes-128-ecb', key);
var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
encryptedPassword += cipher.final('base64')
var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
decryptedPassword += decipher.final('utf8');
console.log('original :', plaintext);
console.log('encrypted :', encryptedPassword);
console.log('decrypted :', decryptedPassword);
但是当我试图解密它时,它总是抛出一个错误。
public static String decrypt(String encryptedText) {
try {
final String key = "mykey@91";
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherText = Base64.getDecoder().decode(encryptedText.getBytes("UTF8"));
String decryptedString = new String(cipher.doFinal(cipherText),"UTF8");
return decryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
我得到的错误如下:
java.security.InvalidKeyException:无效的 AES 密钥长度:8 个字节
【问题讨论】:
-
来自documentation:“crypto.createCipher() 的实现使用 OpenSSL 函数 EVP_BytesToKey 派生密钥,摘要算法设置为 MD5,一次迭代,无盐。缺少盐允许字典攻击因为相同的密码总是创建相同的密钥。低迭代次数和非加密安全哈希算法允许非常快速地测试密码。"
标签: node.js encryption node-crypto