如何解决在Node.js中使用AES-128-ECB加密数据
我必须在nodejs中使用aes-128-ecb加密数据,我的代码是
我正在使用Crypto加密数据
const crypto = require('crypto');
const secret = '1000060000000000';
const cipher = crypto.createCipher('aes-128-ecb',secret);
const ciphertext = cipher.update('9','utf8','base64')+cipher.final('base64');
console.log("Cipher text is: " + ciphertext);
输出应为EtgITaHs6lEvEHBipj08Kg==
但输出为nNzqejauQBnfiDqznGhZ0Q==
解决方法
这里的问题是使用crypto.createCipher,它不直接使用密钥,而是摘要。
引用文档:
crypto.createCipher()的实现使用OpenSSL函数EVP_BytesToKey导出密钥,并将摘要算法设置为MD5,一次迭代且无盐。
反之,如果我们使用cipher.createCipheriv,则可以直接指定密钥,它将为我们提供预期的输出。
这是一个例子:
const crypto = require("crypto");
function encrypt(plainText,key,outputEncoding = "base64") {
const cipher = crypto.createCipheriv("aes-128-ecb",null);
return Buffer.concat([cipher.update(plainText),cipher.final()]).toString(outputEncoding);
}
function decrypt(cipherText,outputEncoding = "utf8") {
const cipher = crypto.createDecipheriv("aes-128-ecb",null);
return Buffer.concat([cipher.update(cipherText),cipher.final()]).toString(outputEncoding);
}
const key = "1000060000000000";
const plainText = "9";
const encrypted = encrypt(plainText,"base64");
console.log("Encrypted string (base64):",encrypted);
const decrypted = decrypt(Buffer.from(encrypted,"base64"),"utf8")
console.log("Decrypted string:",decrypted);
输出将是
EtgITaHs6lEvEHBipj08Kg==
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。