阅读量:0
在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(); } } } } } }
- 在Main方法中,使用AesEncryptionHelper类进行加密和解密测试:
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); } }
运行上述代码,你将看到加密和解密后的文本。请注意,为了简化示例,这里使用了固定的密钥和初始向量。在实际应用中,建议使用更安全的方式来生成和管理密钥和初始向量。