我正在尝试使用加密库对Node中的数据进行字段级加密。
除了使用$和 -
等特殊字符外,它似乎工作得很好前“Price-Smith”
不确定原因
function encrypt(data, key) {
if (data === null)
return null
else if (typeof data === 'undefined')
return undefined;
else if (data === '')
return '';
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
cipher.update(data, 'utf8', 'binary');
return Buffer.concat([iv, cipher.final()]).toString('base64');
}
function decrypt(cipher, key) {
if (cipher === null)
return null
else if (typeof cipher == 'undefined')
return undefined;
else if (cipher === '')
return '';
var cipher = new Buffer(cipher, 'base64');
var iv = cipher.slice(0, 16);
var ciphertext = cipher.slice(16);
var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
decipher.update(ciphertext, 'binary', 'utf8');
return decipher.final('utf8');
}
错误
TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipheriv.Cipher.final (crypto.js:287:27)
每个字段值使用单独的IV,否则相同的字段值将具有相同的密码。因此,我将IV存储为前16个字节,并在解密之前将其拼接。也许这可能是我的问题所在?
谢谢! 安德鲁
答案 0 :(得分:1)
这可能是由于明文的大小而不是所用字符的类型。您需要将update()
的响应与final()
的响应相连接。请勿使用+=
运算符does not always work on arrays。
答案 1 :(得分:1)
谢谢@owlstead!这是工作代码:
function encrypt(data, key) {
if (data === null)
return null
else if (typeof data === 'undefined')
return undefined;
else if (data === '')
return '';
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
var encrypted = [cipher.update(data)];
encrypted.push(cipher.final());
return Buffer.concat([iv, Buffer.concat(encrypted)]).toString('base64');
}
function decrypt(cipher, key) {
if (cipher === null)
return null
else if (typeof cipher == 'undefined')
return undefined;
else if (cipher === '')
return '';
var cipher = new Buffer(cipher, 'base64');
var iv = cipher.slice(0, 16);
var ciphertext = cipher.slice(16);
var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
var decrypted = [decipher.update(ciphertext)];
decrypted.push(decipher.final());
return Buffer.concat(decrypted).toString('utf8');
}