uniapp-app/utils/aesEcb.js
2025-11-13 08:41:08 +08:00

70 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import crypto from "crypto-js";
//解密
const decryptAesEcb = (sSrc, sKey) => {
try {
if (!sKey) {
console.error("Key为空null");
return null;
}
// 1. 将密钥转为 WordArraycrypto 内部格式)
const key = crypto.enc.Utf8.parse(sKey);
// 2. Base64 解码密文,得到 WordArray
const encryptedBytes = crypto.enc.Base64.parse(sSrc);
// 3. 使用 AES/ECB/PKCS7 解密
const decrypted = crypto.AES.decrypt(
{ ciphertext: encryptedBytes }, // 加密数据
key, // 密钥
{
mode: crypto.mode.ECB, // ECB 模式
padding: crypto.pad.Pkcs7, // PKCS7等同于 Java 的 PKCS5Padding
}
);
// 4. 将解密结果转为 UTF-8 字符串
const decryptedText = decrypted.toString(crypto.enc.Utf8);
return decryptedText; // 如果解密失败,可能返回空字符串或非法字符
} catch (error) {
console.error("解密失败:", error);
return null;
}
};
//加密
const encryptAesEcb = (sSrc, sKey) => {
try {
if (!sKey) {
console.error("Key为空null");
return null;
}
// 1. 将密钥转为 WordArraycrypto 内部格式)
const key = crypto.enc.Utf8.parse(sKey);
// 2. 将明文转为 WordArray
const srcBytes = crypto.enc.Utf8.parse(sSrc);
// 3. 使用 AES/ECB/PKCS7 加密
const encrypted = crypto.AES.encrypt(
srcBytes, // 明文数据
key, // 密钥
{
mode: crypto.mode.ECB, // ECB 模式
padding: crypto.pad.Pkcs7, // PKCS7 填充
}
);
// 4. 将加密结果转为 Base64 字符串
// crypto-js 的 encrypt 方法返回的对象中ciphertext 是 WordArray 格式
const encryptedBase64 = encrypted.ciphertext.toString(crypto.enc.Base64);
return encryptedBase64;
} catch (error) {
console.error("加密失败:", error);
return null;
}
};
export { decryptAesEcb, encryptAesEcb };