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

溫馨提示×

c#怎么實現aes加密

c#
小億
97
2024-02-02 09:59:36
欄目: 編程語言

在C#中實現AES加密可以通過使用AesManaged類來實現。下面是一個簡單的示例代碼:

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

public class AesEncryption
{
    public static string Encrypt(string plainText, string key, string iv)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(iv);

        byte[] encryptedBytes;

        using (AesManaged aes = new AesManaged())
        {
            aes.Key = keyBytes;
            aes.IV = ivBytes;

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

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(plainText);
                    }

                    encryptedBytes = ms.ToArray();
                }
            }
        }

        return Convert.ToBase64String(encryptedBytes);
    }

    public static string Decrypt(string encryptedText, string key, string iv)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(iv);

        byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
        string decryptedText;

        using (AesManaged aes = new AesManaged())
        {
            aes.Key = keyBytes;
            aes.IV = ivBytes;

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

            using (MemoryStream ms = new MemoryStream(encryptedBytes))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        decryptedText = sr.ReadToEnd();
                    }
                }
            }
        }

        return decryptedText;
    }
}

使用以上代碼,你可以通過調用AesEncryption.Encrypt方法進行加密,調用AesEncryption.Decrypt方法進行解密。請注意,你需要提供一個密鑰(key)和一個初始化向量(iv),這兩個值必須是相同的才能正確解密。

0
贞丰县| 乌拉特前旗| 泰和县| 井冈山市| 荣成市| 正安县| 湘潭县| 招远市| 农安县| 叶城县| 罗平县| 陆良县| 常熟市| 大化| 怀宁县| 黄陵县| 乐安县| 蒙自县| 鄂尔多斯市| 宣武区| 岳阳市| 永胜县| 山西省| 渑池县| 敦煌市| 青河县| 辽宁省| 涟水县| 上栗县| 商城县| 拉萨市| 绥江县| 新宾| 和硕县| 屏边| 普格县| 曲阜市| 来安县| 山阴县| 安仁县| 湾仔区|