温馨提示×

C#对称加密怎样快速入门

c#
小樊
82
2024-07-15 10:32:44
栏目: 编程语言

要快速入门C#对称加密,你可以使用.NET Framework中的System.Security.Cryptography命名空间提供的类来实现。以下是一个简单的示例代码,演示如何使用AES算法进行对称加密和解密:

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

class Program
{
    static void Main()
    {
        string plainText = "Hello, world!";
        string key = "0123456789abcdef"; // 16字节的AES密钥
        string iv = "abcdef9876543210"; // 16字节的初始化向量

        byte[] encryptedBytes = EncryptStringToBytes_Aes(plainText, key, iv);
        string decryptedText = DecryptStringFromBytes_Aes(encryptedBytes, key, iv);

        Console.WriteLine("Encrypted: " + Convert.ToBase64String(encryptedBytes));
        Console.WriteLine("Decrypted: " + decryptedText);
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, string key, string iv)
    {
        byte[] encrypted;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        return encrypted;
    }

    static string DecryptStringFromBytes_Aes(byte[] cipherText, string key, string iv)
    {
        string plaintext = null;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv);

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

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

        return plaintext;
    }
}

在这个示例中,我们使用了AES算法来加密和解密字符串。你可以根据自己的需求调整密钥和初始化向量的长度,并根据具体情况选择其他对称加密算法。希望这能帮助你快速入门C#对称加密。

0