溫馨提示×

如何在C#中使用對稱加密技術(shù)

c#
小樊
99
2024-07-15 10:25:38
欄目: 編程語言

在C#中使用對稱加密技術(shù)可以通過使用內(nèi)置的加密算法類來實(shí)現(xiàn)。以下是一種在C#中使用對稱加密技術(shù)的示例:

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string originalText = "Hello World!";
        string key = "mysecretkey"; // 16 bytes key for AES encryption

        byte[] encryptedData = Encrypt(originalText, key);
        string decryptedText = Decrypt(encryptedData, key);

        Console.WriteLine($"Original Text: {originalText}");
        Console.WriteLine($"Encrypted Data: {Convert.ToBase64String(encryptedData)}");
        Console.WriteLine($"Decrypted Text: {decryptedText}");
    }

    static byte[] Encrypt(string text, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // 16 bytes Initialization Vector for AES encryption

            using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
            {
                byte[] data = Encoding.UTF8.GetBytes(text);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();

                        return ms.ToArray();
                    }
                }
            }
        }
    }

    static string Decrypt(byte[] encryptedData, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // 16 bytes Initialization Vector for AES encryption

            using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
            {
                using (MemoryStream ms = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}

在上面的示例中,我們使用了AES對稱加密算法來加密和解密文本數(shù)據(jù)。首先,我們生成一個(gè)16字節(jié)的密鑰和初始化向量(IV),然后使用這些密鑰和IV來創(chuàng)建加密器和解密器。加密器和解密器將文本數(shù)據(jù)轉(zhuǎn)換為字節(jié)數(shù)組,并對其進(jìn)行加密和解密。最后,我們將加密后的數(shù)據(jù)和解密后的文本打印出來。

0