C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例
|
admin
2023年3月22日 18:28
本文热度 545
|
这篇文章主要介绍了C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例,每次解密时从密文中截取前16位,这就是实现随机的奥秘,本文同时给出了实现代码,需要的朋友可以参考下。
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。
代码:
public static string Encrypt(string plainText, string AESKey)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);
rijndaelCipher.Key = Convert.fromBase64String(AESKey);
rijndaelCipher.GenerateIV();
byte[] keyIv = rijndaelCipher.IV;
byte[] cipherBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.createEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();
cs.Close();
ms.Close();
}
}
var allEncrypt = new byte[keyIv.Length + cipherBytes.Length];
Buffer.BlockCopy(keyIv, 0, allEncrypt, 0, keyIv.Length);
Buffer.BlockCopy(cipherBytes, 0, allEncrypt, keyIv.Length * sizeof(byte), cipherBytes.Length);
return Convert.ToBase64String(allEncrypt);
}
public static string Decrypt(string showText, string AESKey)
{
string result = string.Empty;
try
{
byte[] cipherText = Convert.fromBase64String(showText);
int length = cipherText.Length;
SymmetricAlgorithm rijndaelCipher = Rijndael.create();
rijndaelCipher.Key = Convert.fromBase64String(AESKey);
byte[] iv = new byte[16];
Buffer.BlockCopy(cipherText, 0, iv, 0, 16);
rijndaelCipher.IV = iv;
byte[] decryptBytes = new byte[length - 16];
byte[] passwdText = new byte[length - 16];
Buffer.BlockCopy(cipherText, 16, passwdText, 0, length - 16);
using (MemoryStream ms = new MemoryStream(passwdText))
{
using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.createDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, 0, decryptBytes.Length);
cs.Close();
ms.Close();
}
}
result = Encoding.UTF8.GetString(decryptBytes).Replace("/0", "");
}
catch { }
return result;
}
调用:
string jiaMi = MyAESTools.Encrypt(textBox1.Text, "abcdefgh12345678abcdefgh12345678");
string jieMi = MyAESTools.Decrypt(textBox3.Text, "abcdefgh12345678abcdefgh12345678");
该文章在 2023/3/22 18:28:42 编辑过