AES GCM是一种高级加密标准的加密算法,可在不失去安全性的前提下实现高效的加密操作。下面分别介绍使用C#和PHP实现AES GCM加密的方法,并对两者进行比较。
C#实现AES GCM加密:
using System.Security.Cryptography;
using System.Text;
public static byte[] AESEncrypt(string plainText, byte[] key, byte[] iv)
{
byte[] encrypted;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Mode = CipherMode.GCM;
aesAlg.Padding = PaddingMode.None;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
PHP实现AES GCM加密:
function AESEncrypt($key, $iv, $data)
{
$cipher = "aes-256-gcm";
$options = OPENSSL_RAW_DATA;
$tag_length = 16;
// Generate a random initialization vector (IV)
if (empty($iv)) {
$iv_length = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($iv_length);
}
$encrypted = openssl_encrypt($data, $cipher, $key, $options, $iv, $tag, "", $tag_length);
// Return IV and encrypted data
return [
"iv" => base64_encode($iv),
"data" => base64_encode($encrypted),
"tag" => base64_encode($tag),
];
}
比较:C#实现的代码使用了.NET自带的加密库,而PHP实现的代码
上一篇:aesgcmdebian