菜大王uniapp开发
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

42 lines
1.3 KiB

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);
}
const Init = CryptoJS.lib.WordArray.init;
return new 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); // 输出解密后的数据
// }
// });