Node.js 中的加密和解密
Encryption and Decryption in 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.'
Output : (utf-8 encoding)
但是当我尝试使用“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;
}
Output : (base-64 encoding)
我无法理解为什么 base-64 编码方案不接受空格和“。”格式正确。
如果有人知道这一点,请帮助我更好地理解这一点。
感谢任何帮助。
如果我没理解错的话,你是在用相同的字符串调用两种加密方法: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解码。
我正在尝试加密并相应地解密一个字符串。
当我将编码方案指定为“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.'
Output : (utf-8 encoding)
但是当我尝试使用“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;
}
Output : (base-64 encoding)
我无法理解为什么 base-64 编码方案不接受空格和“。”格式正确。
如果有人知道这一点,请帮助我更好地理解这一点。
感谢任何帮助。
如果我没理解错的话,你是在用相同的字符串调用两种加密方法: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解码。