温馨提示×

如何在C#中使用对称加密技术

c#
小樊
104
2024-07-15 10:25:38
栏目: 编程语言

在C#中使用对称加密技术可以通过使用内置的加密算法类来实现。以下是一种在C#中使用对称加密技术的示例:

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对称加密算法来加密和解密文本数据。首先,我们生成一个16字节的密钥和初始化向量(IV),然后使用这些密钥和IV来创建加密器和解密器。加密器和解密器将文本数据转换为字节数组,并对其进行加密和解密。最后,我们将加密后的数据和解密后的文本打印出来。

0