91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
汪清县| 浑源县| 璧山县| 和硕县| 益阳市| 游戏| 鸡泽县| 曲周县| 通河县| 民县| 宁晋县| 丰宁| 南丹县| 黑水县| 婺源县| 卓资县| 宜川县| 昌图县| 琼中| 滕州市| 浮山县| 原阳县| 无为县| 万山特区| 阿拉善盟| 若尔盖县| 大连市| 福清市| 南岸区| 瑞丽市| 南江县| 开阳县| 南阳市| 兰溪市| 永嘉县| 尤溪县| 舒兰市| 柞水县| 江陵县| 五大连池市| 虞城县|