在C#中實現對稱加密的加解密測試,你可以使用.NET框架自帶的System.Security.Cryptography命名空間中的類。這里以AES加密為例,展示如何實現加解密測試。
首先,確保已經安裝了System.Security.Cryptography.dll,這個DLL在.NET Framework中已經包含,不需要額外安裝。
創建一個名為AesEncryptionHelper的類,并添加以下代碼:
using System;
using System.Text;
using System.Security.Cryptography;
public static class AesEncryptionHelper
{
private static readonly byte[] Key = Encoding.UTF8.GetBytes("16位長度的密鑰");
private static readonly byte[] IV = Encoding.UTF8.GetBytes("16位長度的初始向量");
public static string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var msEncrypt = new System.IO.MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
public static string Decrypt(string cipherText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new System.IO.MemoryStream(Convert.FromBase64String(cipherText)))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
}
using System;
class Program
{
static void Main(string[] args)
{
string plainText = "這是一段需要加密的文本";
string encryptedText = AesEncryptionHelper.Encrypt(plainText);
string decryptedText = AesEncryptionHelper.Decrypt(encryptedText);
Console.WriteLine("原文:" + plainText);
Console.WriteLine("加密后的文本:" + encryptedText);
Console.WriteLine("解密后的文本:" + decryptedText);
}
}
運行上述代碼,你將看到加密和解密后的文本。請注意,為了簡化示例,這里使用了固定的密鑰和初始向量。在實際應用中,建議使用更安全的方式來生成和管理密鑰和初始向量。