如何在c#中實(shí)現(xiàn)對(duì)稱加密

c#
小樊
83
2024-09-20 05:31:03

在C#中實(shí)現(xiàn)對(duì)稱加密,你可以使用.NET框架自帶的System.Security.Cryptography命名空間中的類。以下是一個(gè)使用AES算法的簡(jiǎn)單示例:

  1. 首先,確保你已經(jīng)安裝了.NET Framework或.NET Core。

  2. 創(chuàng)建一個(gè)新的C#控制臺(tái)應(yīng)用程序項(xiàng)目。

  3. 在項(xiàng)目中添加以下命名空間引用:

using System;
using System.Text;
using System.Security.Cryptography;
  1. 在Main方法中,編寫(xiě)以下代碼:
class Program
{
    static void Main(string[] args)
    {
        string plaintext = "Hello, World!";
        string key = "ThisIsASecretKey!";
        string ciphertext = Encrypt(plaintext, key);
        Console.WriteLine("Plaintext: " + plaintext);
        Console.WriteLine("Ciphertext: " + ciphertext);

        string decryptedText = Decrypt(ciphertext, key);
        Console.WriteLine("Decrypted Text: " + decryptedText);
    }

    static byte[] Encrypt(string plaintext, string key)
    {
        using (Aes aesAlg = Aes.Create())
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] initVectorBytes = Encoding.UTF8.GetBytes("ThisIsASecretInitVector!");

            aesAlg.Key = keyBytes;
            aesAlg.IV = initVectorBytes;

            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 msEncrypt.ToArray();
            }
        }
    }

    static string Decrypt(byte[] cipherText, string key)
    {
        using (Aes aesAlg = Aes.Create())
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] initVectorBytes = Encoding.UTF8.GetBytes("ThisIsASecretInitVector!");

            aesAlg.Key = keyBytes;
            aesAlg.IV = initVectorBytes;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (var msDecrypt = new System.IO.MemoryStream(cipherText))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        return srDecrypt.ReadToEnd();
                    }
                }
            }
        }
    }
}

在這個(gè)示例中,我們使用了AES加密算法,并創(chuàng)建了一個(gè)簡(jiǎn)單的控制臺(tái)應(yīng)用程序來(lái)加密和解密字符串。請(qǐng)注意,為了簡(jiǎn)化示例,我們使用了一個(gè)固定的密鑰和初始化向量(IV)。在實(shí)際應(yīng)用中,你應(yīng)該使用更安全的方式來(lái)生成和存儲(chǔ)密鑰和IV。

0