crypto-js 是一个纯 javascript 写的加密算法类库 ,可以非常方便地在 javascript 进行 MD5、SHA1、SHA2、SHA3、RIPEMD-160 哈希散列,进行 AES、DES、Rabbit、RC4、Triple DES 加解密。
github:https://github.com/brix/crypto-js
示例
定义 encrypt
下面的代码的 KP 中 key 是密钥 ,iv 是密钥偏移量,这个一般是接口返回的,或者前后端协定一致。
//encrypt.js
/**
* 通过crypto-js实现 加解密工具
* AES
* @author: wfk
*/
import CryptoJS from 'crypto-js'
const KP = {
key: '32824659', // 秘钥 16*n:
iv: '1234567812345678' // 偏移量
};
function getAesString(data, key, iv) { // 加密
key = CryptoJS.enc.Utf8.parse(key);
iv = CryptoJS.enc.Utf8.parse(iv);
let encrypted = CryptoJS.DES.encrypt(data, key,
{
// iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString(); // 返回的是base64格式的密文
}
function getDAesString(encrypted, key, iv) { // 解密
key = CryptoJS.enc.Utf8.parse(key);
iv = CryptoJS.enc.Utf8.parse(iv);
let decrypted = CryptoJS.DES.decrypt(encrypted, key,
{
// iv,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8); //
}
// AES 对称秘钥加密
const aes = {
en: (data) => getAesString(data, KP.key, KP.iv),
de: (data) => getDAesString(data, KP.key, KP.iv)
};
// BASE64
const base64 = {
en: (data) => CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data)),
de: (data) => CryptoJS.enc.Base64.parse(data).toString(CryptoJS.enc.Utf8)
};
// SHA256
const sha256 = (data) => {
return CryptoJS.SHA256(data).toString();
};
// MD5
const md5 = (data) => {
return CryptoJS.MD5(data).toString();
};
export {
aes,
md5,
sha256,
base64
};
使用
import { aes } from '@/util/encrypt.js';
****
let password = aes.en('12345678'); //3iy6ZPcjJQzOBGxvlgwRDg==
按需使用
import AES from 'crypto-js/aes';
crypto-js/core
crypto-js/x64-core
crypto-js/lib-typedarrays
crypto-js/md5
crypto-js/sha1
crypto-js/sha256
crypto-js/sha224
crypto-js/sha512
crypto-js/sha384
crypto-js/sha3
crypto-js/ripemd160
crypto-js/hmac-md5
crypto-js/hmac-sha1
crypto-js/hmac-sha256
crypto-js/hmac-sha224
crypto-js/hmac-sha512
crypto-js/hmac-sha384
crypto-js/hmac-sha3
crypto-js/hmac-ripemd160
crypto-js/pbkdf2
crypto-js/aes
crypto-js/tripledes
crypto-js/rc4
crypto-js/rabbit
crypto-js/rabbit-legacy
crypto-js/evpkdf
crypto-js/format-openssl
crypto-js/format-hex
crypto-js/enc-latin1
crypto-js/enc-utf8
crypto-js/enc-hex
crypto-js/enc-utf16
crypto-js/enc-base64
crypto-js/mode-cfb
crypto-js/mode-ctr
crypto-js/mode-ctr-gladman
crypto-js/mode-ofb
crypto-js/mode-ecb
crypto-js/pad-pkcs7
crypto-js/pad-ansix923
crypto-js/pad-iso10126
crypto-js/pad-iso97971
crypto-js/pad-zeropadding
crypto-js/pad-nopadding