在 Node.js 中的加密和解密

5

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

当我指定编码方案为 "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.'  

输出: (utf-8编码)

enter image description here

但是当我尝试使用'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;
}

输出:(使用base-64编码)

enter image description here


我不明白为什么base-64编码方案不能正确处理空格和右侧的“.”格式。
如果有人知道,请帮助我更好地理解。 任何帮助都将不胜感激。

1个回答

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解码。

非常感谢@ralh,它帮助我更好地理解了base64编码和其他相关内容。 :) - Prerna Jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接