我使用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 length
和Error: Invalid IV length
但是我发现键必须有32个字节,而不是16个字节。怎么了?
发布于 2022-05-18 17:29:02
您的密钥和IV的十六进制编码不正确。从这两个变量中删除toString('hex')
,这些参数都不能被十六进制编码.
键和IV的正确长度分别为32字节和16字节。通过对字符串进行十六进制编码,您将生成字符串的长度是所需时间的两倍,其中每个字节从0到255之间的值变为00
和ff
之间的两个字符十六进制表示。
例如,字节数组[255, 255, 255]
变成字符数组['f', 'f', 'f', 'f', 'f', 'f']
。
https://stackoverflow.com/questions/72293514
复制相似问题