/** * aes算法加密/解密 */ import crypto from "crypto"; import * as buffer from "buffer"; window.Buffer = buffer.Buffer; interface EncryptReturn { keyStr: string; ivStr: string; encryptedData: string; rawBuffer: Buffer; base64Str: string; } export class AES { private static keyStr = "15D2783E0FC351E6A96F890F70A29A0D"; private static algorithm = "aes-256-cbc"; private static ivStr = AES.keyStr.slice(0, 16); private static ivByte = Buffer.from(AES.ivStr); private static _instance: AES; private cipher!: crypto.Cipher; constructor() { this.cipher = crypto.createCipheriv(AES.algorithm, Buffer.from(AES.keyStr), AES.ivByte); if (AES._instance) { return AES._instance; } } static get instance(): AES { if (AES._instance) { return AES._instance; } AES._instance = new AES(); return AES._instance; } /** * aes 加密 * @param {string} plaintext - 需要加密的字符串 */ public aesEncrypt(plaintext: string): EncryptReturn { let encrypted = this.cipher.update(plaintext); encrypted = Buffer.concat([encrypted, this.cipher.final()]); return { keyStr: AES.keyStr, ivStr: AES.ivByte.toString("hex"), encryptedData: encrypted.toString("hex"), rawBuffer: encrypted, base64Str: encrypted.toString("base64") }; } /** * aes 解密 * @param {string} encryptedStr - 加密后的字符串 */ public aesDecrypt(encryptedStr: string) { try { const ivStr = AES.ivByte.toString("hex"); const iv = Buffer.from(ivStr, "hex"); const encryptedText = Buffer.from(encryptedStr, "hex"); const decipher = crypto.createDecipheriv(AES.algorithm, Buffer.from(AES.keyStr), iv); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString("utf-8"); } catch (error) { console.error(error); return encryptedStr; } } }