我有 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;
};
問題在于密鑰和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
Error: Invalid key length和Error: Invalid IV length
但我發現密鑰必須有 32 個位元組,而不是 16 個位元組。怎么了?
uj5u.com熱心網友回復:
您錯誤地對密鑰和 IV 進行了十六進制編碼。從兩者中洗掉toString('hex'),這些引數不能是十六進制編碼的。
key 和 IV 的正確長度分別是 32 和 16 位元組。通過對字串進行十六進制編碼,您可以生成兩倍于所需長度的字串,其中每個單個位元組從 0 到 255 之間的值變為介于 和 之間的兩個字符的十六進制00表示ff。
例如,位元組陣列[255, 255, 255]變成字符陣列['f', 'f', 'f', 'f', 'f', 'f']。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477130.html
標籤:javascript 节点.js 打字稿 加密
