1、添加 crypto-js
npm install crypto-js
2、添加 TypeScript对应 crypto-js 的 Interface
npm install --save @types/crypto-js
3、简单使用
基础使用4、AES加解密
AES加密
private encrypt(str: string, key: string, iv: string): any {
let skey = CryptoJS.enc.Latin1.parse(key); //ISO-8859-1
let siv = CryptoJS.enc.Latin1.parse(iv); //ISO-8859-1
let encrypted = CryptoJS.AES.encrypt(str, skey, {
iv: siv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString();
return encrypted;
}
AES解密
private decrypt(str: string, key: string, iv: string): any{
let skey = CryptoJS.enc.Latin1.parse(key); //ISO-8859-1
let siv = CryptoJS.enc.Latin1.parse(iv); //ISO-8859-1
let decrypted = CryptoJS.AES.decrypt(str, skey, {
iv: siv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString(CryptoJS.enc.Utf8);
return decrypted;
}
网友评论