这篇文章主要介绍crypto-js的aes加密和md5加密,首先我们要引入 crypto-js ,crypto-js 是一个纯 javascript 写的加密算法类库。
const CryptoJS = require('crypto-js'); //引用AES源码js
const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412'); //十六位十六进制数作为密钥偏移量
//aes加密
function encrypt(word) {
var encrypted = '';
if (typeof(word) == 'string') {
var srcs = CryptoJS.enc.Utf8.parse(word);
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
} else if (typeof(word) == 'object') {//对象格式的转成json字符串
data = JSON.stringify(word);
var srcs = CryptoJS.enc.Utf8.parse(data);
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
}
return encrypted.ciphertext.toString();
}
// aes解密
function decrypt(word) {
var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
var decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
export default {
decrypt ,
encrypt
}
md5加密方法如下:
function md5encode(word) {
return CryptoJS.MD5(word).toString();
}