0

我正在尝试使用加密库在 Node 中对数据进行字段级加密。

它似乎工作得很好,除了像 $ 和 - 这样的特殊字符

前“普莱斯史密斯”

不知道为什么

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 个字节,并在解密之前将其拼接起来。也许这可能是我的问题区域?

谢谢!安德鲁

4

2 回答 2

2

这可能是由于明文的大小而不是使用的字符类型。您需要将来自的响应与来自update()的响应连接起来final()。不要使用+=运算符,它并不总是适用于数组

于 2014-01-15T23:56:35.420 回答
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');
}
于 2014-01-16T16:37:21.690 回答