使用 Typescript 和 CryptoJS 实现 AES 256 加密与解密,代码类似于 PHP。
安装 CryptoJS:
npm install crypto-js
AES 256 加密示例:
import CryptoJS from 'crypto-js';
function encrypt(message: string, secretKey: string): string {
const key = CryptoJS.enc.Utf8.parse(secretKey);
const iv = CryptoJS.enc.Utf8.parse(secretKey); // 使用相同的 key 作为 iv
const encrypted = CryptoJS.AES.encrypt(message, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
keySize: 256 / 32,
});
return encrypted.toString();
}
const message = 'hello world';
const secretKey = '1234567890abcdef';
const encryptedMessage = encrypt(message, secretKey);
console.log(encryptedMessage);
AES 256 解密示例:
import CryptoJS from 'crypto-js';
function decrypt(ciphertext: string, secretKey: string): string {
const key = CryptoJS.enc.Utf8.parse(secretKey);
const iv = CryptoJS.enc.Utf8.parse(secretKey); // 使用相同的 key 作为 iv
const decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
keySize: 256 / 32,
});
return CryptoJS.enc.Utf8.stringify(decrypted);
}
const ciphertext = 'U2FsdGVkX19UqxZ2/ByswCwm2r....'; // 加密后的消息
const secretKey = '1234567890abcdef';
const decryptedMessage = decrypt(ciphertext, secretKey);
console.log(decryptedMessage);