add 新增 请求加密传输 合并优化 !pr377

This commit is contained in:
疯狂的狮子Li
2023-07-10 18:20:38 +08:00
parent 9e3dd2c6e3
commit d0d67b90bc
5 changed files with 62 additions and 2 deletions

45
src/utils/crypto.ts Normal file
View File

@ -0,0 +1,45 @@
import CryptoJS from 'crypto-js';
/**
* 随机生成32位的字符串
* @returns {string}
*/
const generateRandomString = () => {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < 32; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
/**
* 随机生成aes 密钥
* @returns {string}
*/
export const generateAesKey = () => {
return CryptoJS.enc.Utf8.parse(generateRandomString());
};
/**
* 随机生成aes 密钥
* @returns {string}
*/
export const encryptBase64 = (str: string) => {
return CryptoJS.enc.Base64.stringify(str);
};
/**
* 使用密钥对数据进行加密
* @param message
* @param aesKey
* @returns {string}
*/
export const encryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
};