![](/img/trans.png)
[英]What's the difference between node.js Buffer and WebAssembly Memory?
[英]What is the difference between using string and buffer in Node.js encryption
我在某些网站上看到了下面的两个代码。 一个使用Buffer
来包装crypto.randomBytes()
对象作为密码密钥,然后使用它来连接加密的最终结果,另一个使用Buffer
来使用普通crypto.randomBytes()
对象作为密码密钥,并简单地使用“加等于”来连接最终结果。运营商。
const cipher = crypto.createCipheriv(
"aes-256-gcm",
Buffer.from(crypto.randomBytes(32)),
crypto.randomBytes(16)
);
let encrypted = cipher.update("this is data");
encrypted = Buffer.concat([encrypted, cipher.final()]);
// edited: I forgot below line
encrypted = encrypted.toString("hex");
和...
const cipher = crypto.createCipheriv(
"aes-256-gcm",
crypto.randomBytes(32),
crypto.randomBytes(16)
);
let encrypted = cipher.update("this is data");
encrypted += cipher.final();
两种实现方式均有效。 但是我找不到关于它们为什么使用Buffer
任何解释,也不知道两个示例之间的区别。
我尝试在两个实现中使用相同的key
和iv
(正如Maarten Bodewes 建议的那样 ,它们产生的结果相同:
const crypto = require('crypto');
const data = 'hello world'
const algorithm = 'aes-256-gcm'
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
function encrypt1(data) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
function encrypt2(data) {
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(data);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return encrypted.toString('hex');
}
const result1 = encrypt1(data);
const result2 = encrypt2(data);
console.log('result1: ', result1); // -> result1: 501db5c82e79e3185c1601
console.log('result2: ', result2); // -> result2: 501db5c82e79e3185c1601
因此,为什么必须使用看起来更复杂的Buffer才能产生相同的结果?
Buffer
只是所使用的内部结构。
以下是一些可能的优点:
最后, Buffer
更接近键实际上应该是八位字节字符串或字节数组 ,而不是文本字符串的键 。
然而,所有这些,对于简单的密码操作,在预期输出方面没有区别。 因此从这个意义上讲,两种方法都是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.