RangeError:密钥长度无效



我试图实现Aes-128-gcm,但每次我尝试运行代码时,它都会返回"RangeError:无效密钥长度";

const crypto = require('crypto'); 
const encryptionKey = crypto.randomBytes(32);
const IV =  crypto.randomBytes(16); 
const data = "who let the dogs out";

var encrypt = ((dataValue) => {
let cipher = crypto.createCipheriv('aes-128-gcm', encryptionKey, IV);
let encrypted = cipher.update(dataValue, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
});
var decrypt = ((encrypted) => {
let decipher = crypto.createDecipheriv('aes-128-gcm', encryptionKey, IV);
let decrypted = decipher.update(encrypted, 'base64', 'utf8');
return (decrypted + decipher.final('utf8'));
});

我做错了什么?

密钥长度取决于算法,例如:

  • aes128对应16个字节
  • aes192对应于24个字节
  • aes256对应于32个字节

因此您需要一个16字节(128位(的密钥长度。您可以创建如下密钥:

const key = crypto.createHash('sha256').update(String(secret)).digest('base64').slice(0, 16)

最新更新