在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)長度的字符串。