GitHub
https://github.com/brix/crypto-js
小程序代码中,需要使用aes加密算法
第一时间想到的是这个库
但是在使用过程中发现,这个库的加密算法,AES,加密算法,
在偶尔的情况下,会丢失加密后的 == 符号,导致无法解密出来。
发现这个加密算法是有坑的
去微信小程序官网,看到有推荐一个加密算法
const aesjs = require('aes-js.js');
const defaultKey = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];// 默认的key
/**
* 加密方法
* @param: str 需要加密的字符
* @param: key 密钥
* @param: iv 密钥偏移量
*/
function encrypt(text) {
var textBytes = aesjs.utils.utf8.toBytes(text);
// The counter is optional, and if omitted will begin at 1
var aesCtr = new aesjs.ModeOfOperation.ctr(defaultKey, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);
// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
return encryptedHex.toString();
}
/**
* 解密方法
* @param: str 需要解密的字符
* @param: key 密钥
* @param: iv 密钥偏移量
*/
function decrypt(encryptedHex) {
// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);
// The counter mode of operation maintains internal state, so to
// decrypt a new instance must be instantiated.
var aesCtr = new aesjs.ModeOfOperation.ctr(defaultKey, new aesjs.Counter(5));
var decryptedBytes = aesCtr.decrypt(encryptedBytes);
// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
return decryptedText;
}
export{
decrypt,
encrypt,
}