AES常用加密模式为 ECB 与 CBC,二者在使用上的区别为是否需要偏移量(iv)
工具
crypto-js
crypto-js的GitHub官方地址。
安装
crypto-js
目前版本为4.x
,但在实际使用中发现,安装最新版本时,若使用CBC模式加密,会报Native crypto module could not be used to get secure random number.
错误,这个错误目前作者仍没有修复,在GitHub的issue上也没比较好的解决办法,故使用3.x
版本
若是使用TypeScript的話,記得要多一個@type/scrypt-js
// 安装3.x的最新版本
npm install crypto-js@3.9.1
使用
新建crypto.js
或者在你现有的任意文件中进行均可
// 引入crypto-js
const CryptoJS = require('crypto-js')
// crypto加密需要长度为16的密钥,且考虑到安全性密钥最好还是随机生成
//创建密钥
const createAesKey => () {
const expect = 16
let str = Math.random().toString(36).substr(2)
while (str.length < expect) {
str += Math.random().toString(36).substr(2)
}
str = str.substr(0, 16)
return str
}
// 加密
// ECB模式不需要偏移量。如果选择加密模式为CBC,则还需要生成16位数的iv
const msgEncrypted => (word, key) {
let srcs = CryptoJS.enc.Utf8.parse(word);
let kkey = CryptoJS.enc.Utf8.parse(key)
let encrypted = CryptoJS.AES.encrypt(srcs, kkey, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
return encrypted.ciphertext.toString().toUpperCase();
}
// 解密
// 解密模式同上,如果选择CBC,也需要传入相应的iv
const msgDecrypted => (content, key) {
var sKey = CryptoJS.enc.Utf8.parse(key);
var decrypt = CryptoJS.AES.decrypt(content, sKey, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
let deRes = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt).toString())
return deRes
}
在使用时引用相应函数即可。