crypto.createCipheriv 中的密钥长度无效

2024-01-29

我在 NodeJS v8.11.0 中使用以下代码生成了一个 base64 编码的密钥:

const secret = 'shezhuansauce';
const key = crypto.createHash('sha256').update(String(secret)).digest('base64');
//output is REtgV24bDB7xQYoMuypiBASMEaJbc59nJWChoXbbmsA=

使用密钥,我尝试加密一个字符串:

var tobeEncrypted = 'some secret string';
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
const encrypted = cipher.update(String(tobeEncrypted), 'utf8', 'hex') + cipher.final('hex');
console.log(encrypted);

但是,我收到一个错误:

crypto.js:219
this._handle.initiv(cipher, toBuf(key), toBuf(iv));
           ^
Error: Invalid key length

密钥必须是 base64 字符串,因为我将其存储在云服务中,并且它只接收 base64 字符串。

任何帮助表示赞赏。


只需添加一个提示:密钥长度取决于算法,例如对于 aes192,它是 24 字节,或者 aes256,它是 32 字节。 您需要有 32 字节(256 位)的密钥长度。 因此,如果您将关键行更改为:

let key = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 32);

它会起作用的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

crypto.createCipheriv 中的密钥长度无效 的相关文章

随机推荐