Browse Source

feat(utils): 添加加密工具模块和配置

- 新增config.js用于存储密钥配置
- 新增crypto.js提供AES加密解密功能
master
wei 1 week ago
parent
commit
f81c68e260
  1. 5
      libs/utils/config.js
  2. 42
      libs/utils/crypto.js

5
libs/utils/config.js

@ -0,0 +1,5 @@
const SECRET_KEY = 'a1b2c3d4e5f678901234567890abcdefa1b2c3d4e5f678901234567890abcdef';
export default {
SECRET_KEY,
};

42
libs/utils/crypto.js

@ -0,0 +1,42 @@
import CryptoJS from 'crypto-js';
import secretKey from './config.js';
// 解决App端没有window.crypto的问题
if (typeof window === 'undefined' || !window.crypto) {
// 提供自定义随机数生成器
CryptoJS.lib.WordArray.random = function(nBytes) {
const words = [];
for (let i = 0; i < nBytes; i += 4) {
// 使用uniapp的随机数API或Math.random()生成
words.push(((Math.random() * 0x100000000) | 0) << 0);
}
return new CryptoJS.lib.WordArray.init(words, nBytes);
};
}
// 加密函数
export function encryptData(data, secretKey) {
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
}
// 解密函数
export function decryptData(ciphertext, secretKey) {
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
// 使用示例
// const secretKey = secretKey; // 替换为你的密钥
// const dataToStore = { key: 'value' };
// const encryptedData = encryptData(dataToStore, secretKey);
// uni.setStorage({ key: 'encryptedData', data: encryptedData });
// // 获取并解密数据
// uni.getStorage({
// key: 'encryptedData',
// success: (res) => {
// const decryptedData = decryptData(res.data, secretKey);
// console.log(decryptedData); // 输出解密后的数据
// }
// });
Loading…
Cancel
Save