js加密
async function encryptText(plaintext) {
const textEncoder = new TextEncoder();
const dataBuffer = textEncoder.encode(plaintext);
const key = '123456789012345678901234567890ab';
const iv = '1234567890123456';
const keyBuffer = new Uint8Array(key.split('').map(c => c.charCodeAt(0)));
const ivBuffer = new Uint8Array(iv.split('').map(c => c.charCodeAt(0)));
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
);
const encryptedArray = new Uint8Array(encrypted);
return btoa(String.fromCharCode(...encryptedArray));
}
c#解密
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#加密
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解密
async function decryptText(ciphertext) {
const key = '123456789012345678901234567890ab';
const iv = '1234567890123456';
const keyBuffer = new Uint8Array(key.split('').map(c => c.charCodeAt(0)));
const ivBuffer = new Uint8Array(iv.split('').map(c => c.charCodeAt(0)));
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);
}