using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryptionExample
{
public static void Main()
{
string original = "Here is some data to encrypt!";
string encrypted = EncryptString(original, "A16ByteKey!A16ByteKey!");
string decrypted = DecryptString(encrypted, "A16ByteKey!A16ByteKey!");
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Encrypted: {0}", encrypted);
Console.WriteLine("Decrypted: {0}", decrypted);
}
public static string EncryptString(string plainText, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[16]; // Initialization Vector
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);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
}
public static string DecryptString(string cipherText, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[16]; // Initialization Vector
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
}
加密和解密方法:
EncryptString 方法用于将字符串加密为 AES 加密的 Base64 编码字符串。DecryptString 方法用于将 AES 加密的 Base64 编码字符串解密回原始字符串。初始化向量 (IV):
密钥:
编码:
流处理:
MemoryStream 和 CryptoStream 来处理加密和解密过程中的数据流。这个示例展示了如何使用 C# 中的 Aes 类来实现基本的 AES 加密和解密功能。
上一篇:c# sealed
下一篇:c# try
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站