Node.js 中的加密和解密

Pre*_*ain 5 encryption base64 encoding utf-8 node.js

我正在尝试加密并相应地解密一个字符串。

当我将编码方案指定为 ' utf-8 ' 时,我得到了预期的结果:

    function encrypt(text) {
        var cipher = crypto.createCipher(algorithm, password)
        var crypted = cipher.update(text, 'utf8', 'hex')
        crypted += cipher.final('hex');
        return crypted;
    }

    function decrypt(text) {
        var decipher = crypto.createDecipher(algorithm, password)
        var dec = decipher.update(text, 'hex', 'utf8')
        dec += decipher.final('utf8');
        return dec;
    }

//text = 'The big brown fox jumps over the lazy dog.'  
Run Code Online (Sandbox Code Playgroud)

输出:(utf-8 编码)

在此处输入图片说明

但是当我尝试使用 ' base-64 ' 时,它给了我意想不到的结果:

function encrypt(text) {
    var cipher = crypto.createCipher(algorithm, password)
    var crypted = cipher.update(text, 'base64', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(algorithm, password)
    var dec = decipher.update(text, 'hex', 'base64')
    dec += decipher.final('base64');
    return dec;
}
Run Code Online (Sandbox Code Playgroud)

输出:(base-64 编码)

在此处输入图片说明


我无法理解为什么 base-64 编码方案不接受空格和 '.' 以正确的格式。
如果有人知道这一点,请帮助我更好地理解这一点。任何帮助表示赞赏。

ral*_*alh 1

如果我理解正确,您将使用相同的字符串调用两种加密方法:The big brown fox jumps over the lazy dog.。事情是,cipher.update的签名如下所示:

cipher.update(data[, input_encoding][, output_encoding])

因此,在第二种加密方法中,您将使用'base64'作为输入编码。并且您的字符串不是 base64 编码的。Base64 不能有空格、句号等。

您可能想先用 Base64 对其进行编码。您可以在此处查看答案以了解如何执行此操作: How to do Base64 Encoding in Node.js?

然后您可以使用第二种加密方法。解密后,您将再次收到一个 Base64 编码的字符串,并且您必须对其进行解码。上面的问题还展示了如何从 Base64 进行解码。