错误:使用AES-256-CBC算法无效的密钥长度和错误:无效的IV长度

发布于 2025-01-30 03:35:38 字数 1077 浏览 1 评论 0原文

我有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹淡然 2025-02-06 03:35:38

您正在错误地编码您的钥匙和IV。 drop toString('hex')都必须从两者中进行编码。

键的正确长度和IV的正确长度分别为32和16字节。通过编码字符串,您要生成的字符串是需要的两倍,而每个单字节从0到255之间的值介于> 00ff 。

例如,字节数组[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 and ff.

For example, the byte array [255, 255, 255] becomes the character array ['f', 'f', 'f', 'f', 'f', 'f'].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文