Joe*_*ang 3 encryption cryptography node.js
我正在加密这样的文本(node.js):
var text = "holds a long string..."
var cipher = crypto.createCipher("aes128", "somepassword")
var crypted = cipher.update(text, 'utf8', 'hex')
crypted += cipher.final('hex');
Run Code Online (Sandbox Code Playgroud)
如果我text直接保存到文件,就是N个字节。如果我保存crypted,文件大小约为 N * 2 字节。
有什么办法可以让加密后的文本尽可能接近N个字节吗?
问题是你的'hex'编码。基本上你建议密码
text使用utf8编码获取字符串的二进制表示hex使用编码将二进制编码字节转换为字符串十六进制编码使用 2 个字节来表示 1 个实际字节,因此您得到的文件大小大约是纯文本大小的两倍。
解决方案是对密文使用更有效的编码,该编码仍然能够保存所有可能的字节值,这排除了简单的字符串。尝试:
var crypted = cipher.update(text, 'utf8', 'base64');
crypted += cipher.final('base64');
Run Code Online (Sandbox Code Playgroud)
这会将密文编码为Base64编码字符串。
我创建了一个在线示例,结果是:
text: 488890
crypted hex length: 977792, ratio: 2.0000245453987606
crypted base64 length: 651864, ratio: 1.3333551514655648
Run Code Online (Sandbox Code Playgroud)
安全公告:请勿在生产中使用此密钥/IV 生成。我强烈建议为每个加密使用不同的 IV,使用crypto.createCipheriv(algorithm, key, iv). 但对于演示目的来说这很好。