在C#中,可以使用System.Security.Cryptography命名空间下的类来实现字符串的加密和解密。以下是一个使用AES加密和解密的示例:
首先,确保已经安装了System.Security.Cryptography.Aes NuGet包。如果没有安装,可以通过以下命令安装:
dotnet add package System.Security.Cryptography.Aes
然后,可以使用以下代码实现加密和解密:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
class AesEncryptionExample
{
static void Main()
{
string key = "your-secret-key"; // 密钥应该是16、24或32个字符长度的字符串
string plaintext = "Hello, World!"; // 要加密的字符串
string encrypted = Encrypt(plaintext, key);
Console.WriteLine("Encrypted text: " + encrypted);
string decrypted = Decrypt(encrypted, key);
Console.WriteLine("Decrypted text: " + decrypted);
}
static string Encrypt(string plaintext, string key)
{
byte[] iv = new byte[16]; // 初始化向量(IV)长度为16字节(AES-128)
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(plaintext);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
static string Decrypt(string ciphertext, string key)
{
byte[] iv = new byte[16]; // 初始化向量(IV)长度为16字节(AES-128)
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(ciphertext)))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
array = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
}
}
}
}
return Encoding.UTF8.GetString(array);
}
}
请注意,这个示例使用了AES-128加密算法。你可以根据需要选择其他加密算法,例如AES-192或AES-256。但是,密钥和IV的长度将相应地变化。例如,对于AES-256,密钥应该是32个字符长度的字符串,IV应该是16字节(AES-128)或24字节(AES-192或AES-256)长度的字符串。