错误:使用AES-256-CBC算法无效的密钥长度和错误:无效的IV长度
我有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和键,这样:
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
错误:无效的密钥长度
and 错误:无效IV iv iv length
但是我发现钥匙必须有32个字节,而不是16个字节。怎么了?
I have 2 functions to encrypt and decrypt with AES-256-CBC algorithm:
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;
};
The problem is with key and IV. I had to generate IV and key like this:
crypto.randomBytes(8).toString('hex') // IV
crypto.randomBytes(16).toString('hex') // Key
I was trying to change length like this, but had 2 errors:
crypto.randomBytes(16).toString('hex') // IV
crypto.randomBytes(32).toString('hex') // Key
Error: Invalid key length
and Error: Invalid IV length
But I have found that key has to have 32 bytes, not 16. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在错误地编码您的钥匙和IV。 drop
toString('hex')
都必须从两者中进行编码。键的正确长度和IV的正确长度分别为32和16字节。通过编码字符串,您要生成的字符串是需要的两倍,而每个单字节从0到255之间的值介于
> 00
和ff 。
例如,字节数组
[255,255,255]
成为字符数组['f',f','f',f',f',f','f','f','f',f','f ']
。You are incorrectly hex-encoding your key and IV. Drop
toString('hex')
from both, these arguments must not be hex-encoded.The correct length of the key and IV is 32 and 16 bytes respectively. By hex-encoding the strings, you're producing strings twice as long as is required, where each single byte goes from a value between 0 and 255 to a two character hex representation between between
00
andff
.For example, the byte array
[255, 255, 255]
becomes the character array['f', 'f', 'f', 'f', 'f', 'f']
.