目录
js加密
javascript
async function encryptText(plaintext) {
// 将文本转换为ArrayBuffer
const textEncoder = new TextEncoder();
const dataBuffer = textEncoder.encode(plaintext);
// 密钥和初始化向量,应该是一个安全的随机值
const key = '123456789012345678901234567890ab'; // 32字节密钥
const iv = '1234567890123456'; // 16字节初始化向量
// 将密钥和初始化向量转换为ArrayBuffer
const keyBuffer = new Uint8Array(key.split('').map(c => c.charCodeAt(0)));
const ivBuffer = new Uint8Array(iv.split('').map(c => c.charCodeAt(0)));
// 使用AES-CBC算法和PKCS7填充
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
keyBuffer,
{ name: 'AES-CBC', length: 256 },
false,
['encrypt']
);
// 加密数据
const encrypted = await window.crypto.subtle.encrypt(
{ name: 'AES-CBC', iv: ivBuffer },
cryptoKey,
dataBuffer
);
// 将加密后的数据转换为Base64字符串
const encryptedArray = new Uint8Array(encrypted);
return btoa(String.fromCharCode(...encryptedArray));
}
c#解密
csharp
public string DecryptAes( string encryptedData, string key,string iv)
{
// 转换为字节数组
byte[] encryptedBytes = Convert.FromBase64String(encryptedData);
// 创建解密器
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// 创建解密器
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
// 解密
byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
// 输出解密后的数据
return Encoding.UTF8.GetString(decryptedBytes);
}
}
c#加密
csharp
public string EncryptAes(string content, string key, string iv)
{
// 转换为字节数组
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
// 创建解密器
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// 创建解密器
ICryptoTransform decryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// 解密
byte[] encryptedBytes = decryptor.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
// 输出解密后的数据
return Convert.ToBase64String(encryptedBytes);
}
}
js解密
javascript
async function decryptText(ciphertext) {
// 密钥和初始化向量,应该是一个安全的随机值
const key = '123456789012345678901234567890ab'; // 32字节密钥
const iv = '1234567890123456'; // 16字节初始化向量
// 将密钥和初始化向量转换为ArrayBuffer
const keyBuffer = new Uint8Array(key.split('').map(c => c.charCodeAt(0)));
const ivBuffer = new Uint8Array(iv.split('').map(c => c.charCodeAt(0)));
// 将Base64字符串转换为ArrayBuffer
const encryptedArray = new Uint8Array(atob(ciphertext).split('').map(c => c.charCodeAt(0)));
// 导入密钥
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
keyBuffer,
{ name: 'AES-CBC', length: 256 },
false,
['decrypt']
);
// 解密数据
const decrypted = await window.crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: ivBuffer },
cryptoKey,
encryptedArray
);
// 将解密后的数据转换为文本
const textDecoder = new TextDecoder();
return textDecoder.decode(decrypted);
}