uniapp 使用aes加解密写个正确列子
时间: 2024-10-10 09:09:24 浏览: 53
在uniapp中使用AES加解密,你可以参考以下的基本例子。首先,你需要安装`crypto-js`库,可以使用`npm`或者`yarn`进行安装:
```bash
// npm
npm install crypto-js
// 或者 yarn
yarn add crypto-js
```
下面是一个简单的AES加解密示例:
```javascript
import CryptoJS from 'crypto-js';
// 加密函数
function encrypt(text, key) {
const iv = CryptoJS.lib.WordArray.random(CryptoJS.AES.blockSize);
const ciphertext = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return {
ciphertext: ciphertext.toString(CryptoJS.enc.Base64),
iv: iv.toString(CryptoJS.enc.Base64)
};
}
// 解密函数
function decrypt(ciphertext, iv, key) {
const base64iv = iv ? iv : ciphertext.split('.')[0];
const base64ciphertext = ciphertext.split('.')[1];
const bytes Iv = CryptoJS.enc.Base64.parse(base64iv);
const bytesCiphertext = CryptoJS.enc.Base64.parse(base64ciphertext);
const decrypted = CryptoJS.AES.decrypt({ciphertext: bytesCiphertext, iv: bytesIv}, key, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.UTF8);
}
// 示例
const secretKey = 'your_secret_key_123'; // 用于加密和解密的密钥,保证长度为16、24或32字节
const plainText = 'Hello, UniApp!';
const encryptedData = encrypt(plainText, secretKey);
console.log('Encrypted:', encryptedData.ciphertext);
console.log('IV:', encryptedData.iv);
const decryptedText = decrypt(encryptedData.ciphertext, encryptedData.iv, secretKey);
console.log('Decrypted:', decryptedText);
//
阅读全文
相关推荐













