发布于 

AES加密与解密

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
import CryptoJS from 'crypto-js';
const _charStr =
'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';

/**
* 随机生成索引
* @param min 最小值
* @param max 最大值
* @param i 当前获取位置
*/
function RandomIndex(min: number, max: number, i: number) {
let index = Math.floor(Math.random() * (max - min + 1) + min),
numStart = _charStr.length - 10;
//如果字符串第一位是数字,则递归重新获取
if (i == 0 && index >= numStart) {
index = RandomIndex(min, max, i);
}
//返回最终索引值
return index;
}

/**
* 随机生成字符串
* @param len 指定生成字符串长度
*/
export function getRandomString(len: number) {
let min = 0,
max = _charStr.length - 1,
_str = '';
//判断是否指定长度,否则默认长度为15
len = len || 15;
//循环生成字符串
for (var i = 0, index; i < len; i++) {
index = RandomIndex(min, max, i);
_str += _charStr[index];
}
return _str;
}

// AES加密
export function encryptByAES(data: any, aesKey = "") {
let AESKey = aesKey;
let key = CryptoJS.enc.Utf8.parse(AESKey);
let cipherText = CryptoJS.AES.encrypt(data, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return cipherText.toString();
}

// AES解密
export function decryptedByAES(data: any, aesKey = "") {
let AESKey = aesKey;
let key = CryptoJS.enc.Utf8.parse(AESKey);
let decryptedData = CryptoJS.AES.decrypt(data, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return decryptedData.toString(CryptoJS.enc.Utf8);
}