Я видел оба кода ниже на некоторых сайтах. Один использовал Buffer
, чтобы обернуть crypto.randomBytes()
объект для ключа шифрования, и использовал его для конкатенации окончательного результата шифрования, другой использовал простой 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
и не знаю, в чем разница между этими двумя примерами.
UPDATE
Я пытался использовать одинаковые key
и iv
с обеими реализациями (как предложил Мартен Бодьюс , они дают одинаковый результат:
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
Итак, почему нужно использовать буфер, который выглядит более сложным для получения того же результата?