我有 2 个函数可以使用 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
我试图改变这样的长度,但有2个错误:
crypto.randomBytes(16).toString('hex') // IV
crypto.randomBytes(32).toString('hex') // Key
Error: Invalid key length
和 Error: Invalid IV length
但是我发现 key 必须有 32 个字节,而不是 16 个字节。怎么了?
回答1
您错误地对 key 和 IV 进行了十六进制编码。从两者中删除 toString('hex')
,这些参数不能是十六进制编码的。
key 和 IV 的正确长度分别是 32 和 16 字节。通过对字符串进行十六进制编码,您可以生成两倍于所需长度的字符串,其中每个单个字节从 0 到 255 之间的 value 到 00
和 ff
之间的两个字符的十六进制表示。
例如,字节数组 [255, 255, 255]
变为字符数组 ['f', 'f', 'f', 'f', 'f', 'f']
。