Ste*_*nko 25 encryption node.js
我正在使用以下函数来加密/解密 Node.js 中的字符串:
var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
function encrypt(text) {
var cipher = crypto.createCipher(algorithm, password);
try {
var crypted = cipher.update(text, 'utf8', 'hex');
crypted += cipher.final('hex');
} catch (e) {
return;
}
return crypted;
}
function decrypt(text) {
var decipher = crypto.createDecipher(algorithm, password);
try {
var dec = decipher.update(text, 'hex', 'utf8');
dec += decipher.final('utf8');
} catch (e) {
return;
}
return dec;
}
Run Code Online (Sandbox Code Playgroud)
(密码与编码文本分开存储)。新版本的 nodejs/crypt 包抱怨:
(node:5212) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.
Run Code Online (Sandbox Code Playgroud)
我如何重写它以升级我的源代码?
Zee*_*mon 39
所以让我们这样说:
将弃用的crypto.createDecipher用法替换为crypto.createDecipheriv
为什么?因为:
根据弃用文档,这是出于安全考虑。
应避免使用crypto.createCipher()and ,crypto.createDecipher() 因为它们使用弱密钥派生函数(无盐的 MD5)和静态初始化向量。建议分别使用crypto.pbkdf2()或导出密钥crypto.scrypt()并使用crypto.createCipheriv()和crypto.createDecipheriv()分别获取 Cipher 和 Decipher 对象。
以上参考链接:点击这里
也有人说:
根据crypto_crypto_createdecipher_algorithm_password_options,现在需要切换到crypto.createDecipheriv.
示例代码:
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const ENCRYPTION_KEY = 'Put_Your_Password_Here'; // or generate sample key Buffer.from('FoCKvdLslUuB4y3EZlKate7XGottHski1LmyqJHvUhs=', 'base64');
const IV_LENGTH = 16;
function encrypt(text) {
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
function decrypt(text) {
let textParts = text.split(':');
let iv = Buffer.from(textParts.shift(), 'hex');
let encryptedText = Buffer.from(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
Run Code Online (Sandbox Code Playgroud)
对于完整的运行示例 clone node-cheat并运行node crypto-create-cipheriv.js.
| 归档时间: |
|
| 查看次数: |
13894 次 |
| 最近记录: |