1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| var CryptoJS = require("crypto-js");
function md5(data) { return CryptoJS.MD5(data).toString(); }
function parseKey(key) { return CryptoJS.enc.Utf8.parse(key); }
function encrypt(mode, plainText, key, iv = null) { const uKey = parseKey(key); const uIv = parseKey(iv); return CryptoJS.AES.encrypt(plainText, uKey, { iv: uIv, mode: mode, padding: CryptoJS.pad.Pkcs7 } ).toString(); }
function decrypt(mode, cipherText, key, iv = null) { const uKey = parseKey(key); const uIv = parseKey(iv); let bytes = CryptoJS.AES.decrypt(cipherText, uKey, { iv: uIv, mode: mode, padding: CryptoJS.pad.Pkcs7 } ); return bytes.toString(CryptoJS.enc.Utf8); }
function toAES() { const key = '123456'; const md5Key = md5(key); const iv = md5Key.substr(0, 16); const data = '123456789';
let cipherText = encrypt(CryptoJS.mode.ECB, data, md5Key); console.log(cipherText);
let plainText = decrypt(CryptoJS.mode.ECB, cipherText, md5Key); console.log(plainText);
cipherText = encrypt(CryptoJS.mode.CBC, data, md5Key, iv); console.log(cipherText);
plainText = decrypt(CryptoJS.mode.CBC, cipherText, md5Key, iv); console.log(plainText); }
toAES();
|