import { encrypt, decrypt } from 'crypto-js/aes'; import { parse } from 'crypto-js/enc-utf8'; import pkcs7 from 'crypto-js/pad-pkcs7'; import md5 from 'crypto-js/md5'; import UTF8 from 'crypto-js/enc-utf8'; import Base64 from 'crypto-js/enc-base64'; import * as CryptoJS from 'crypto-js'; export interface EncryptionParams { key: string; iv: string; } export class AesEncryption { key; iv; constructor(opt: Partial = {}) { const { key, iv } = opt; if (key) { this.key = parse(key); } if (iv) { this.iv = parse(iv); } } get getOptions() { return { mode: CryptoJS.mode.CBC, padding: pkcs7, iv: this.iv, }; } encryptByAES(cipherText: string) { return encrypt(cipherText, this.key, this.getOptions).toString(); } decryptByAES(cipherText: string) { return decrypt(cipherText, this.key, this.getOptions).toString(UTF8); } // 将 Uint8Array 转换为 CryptoJS.lib.WordArray static uint8ArrayToWordArray(uint8Array: Uint8Array): CryptoJS.lib.WordArray { const words: number[] = []; for (let i = 0; i < uint8Array.length; i += 4) { let word = 0; for (let j = 0; j < 4 && i + j < uint8Array.length; j++) { word |= (uint8Array[i + j] & 0xff) << (24 - 8 * j); } words.push(word); } return CryptoJS.lib.WordArray.create(words, uint8Array.length); } // 将 CryptoJS.lib.WordArray 转换为 Uint8Array static wordArrayToUint8Array(wordArray: CryptoJS.lib.WordArray): Uint8Array { const words = wordArray.words; const sigBytes = wordArray.sigBytes; const uint8Array = new Uint8Array(sigBytes); for (let i = 0; i < sigBytes; i++) { const byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; uint8Array[i] = byte; } return uint8Array; } } export function encryptByBase64(cipherText: string) { return UTF8.parse(cipherText).toString(Base64); } export function decodeByBase64(cipherText: string) { return Base64.parse(cipherText).toString(UTF8); } export function encryptByMd5(password: string) { return md5(password).toString(); }