Error: Invalid key length and Error: Invalid IV length using



我用AES-256-CBC算法加密和解密有两个函数:

import * as crypto from "crypto";
export const encrypt = (text: string, key: string, iv: string) => {
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let result = cipher.update(text, "utf8", "hex");
result += cipher.final("hex");
return result;
};
export const decrypt = (text: string, key: string, iv: string) => {
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let result = decipher.update(text, "hex", "utf8");
result += decipher.final("utf8");
return result;
};

问题在于key和IV。我必须这样生成IV和key:

crypto.randomBytes(8).toString('hex') // IV
crypto.randomBytes(16).toString('hex') // Key

我试图改变长度像这样,但有两个错误:

crypto.randomBytes(16).toString('hex') // IV
crypto.randomBytes(32).toString('hex') // Key

Error: Invalid key lengthError: Invalid IV length

但我发现密钥必须有32字节,而不是16。怎么了?

您的key和IV的十六进制编码不正确。从两者中删除toString('hex'),这些参数不能是十六进制编码。

key和IV的正确长度分别为32和16字节。通过对字符串进行十六进制编码,生成的字符串长度是所需长度的两倍,其中每个字节从0到255之间的值变为00ff之间的两个字符十六进制表示。

例如,字节数组[255, 255, 255]变成字符数组['f', 'f', 'f', 'f', 'f', 'f']

相关内容

最新更新