根据你上面的方法写一个使用实例
时间: 2024-01-26 14:04:23 浏览: 21
好的,以下是一个使用实例,演示了如何在 Vue3 中使用 AES 加密,然后在 C# 中使用 AES 解密:
Vue3 中使用 AES 加密:
```javascript
import CryptoJS from 'crypto-js'
/**
* AES加密
* @param {String} data 需要加密的字符串
* @param {String} key 密钥
* @param {String} iv 偏移量
* @returns {String} 加密后的字符串
*/
export function AESEncrypt(data, key, iv) {
key = CryptoJS.enc.Utf8.parse(key)
iv = CryptoJS.enc.Utf8.parse(iv)
const encrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return encrypted.toString()
}
```
在 Vue3 中调用上述方法:
```javascript
import { AESEncrypt } from '@/utils/crypto'
// 需要加密的字符串
const data = 'Hello world!'
// 密钥和偏移量
const key = '1234567890123456'
const iv = '1234567890123456'
// 加密
const encryptedData = AESEncrypt(data, key, iv)
// 输出加密后的字符串
console.log(encryptedData)
```
C# 中使用 AES 解密:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
public static string DecryptAES(string cipherText, byte[] key, byte[] iv)
{
byte[] encryptedBytes = Convert.FromBase64String(cipherText);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Mode = CipherMode.CBC;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new System.IO.MemoryStream(encryptedBytes))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
```
在 C# 中调用上述方法:
```csharp
// 需要解密的字符串
string encryptedData = "Rq8JiZ0xL9X5yj+G6pBcOA==";
// 密钥和偏移量
byte[] key = Encoding.UTF8.GetBytes("1234567890123456");
byte[] iv = Encoding.UTF8.GetBytes("1234567890123456");
// 解密
string decryptedData = DecryptAES(encryptedData, key, iv);
// 输出解密后的字符串
Console.WriteLine(decryptedData);
```
输出结果应该是 `Hello world!`。