中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
武鸣县| 黔西| 赤峰市| 清流县| 茶陵县| 邵阳县| 开平市| 正镶白旗| 都昌县| 新昌县| 二连浩特市| 恩施市| 贡嘎县| 莆田市| 金川县| 新河县| 新泰市| 中西区| 新巴尔虎右旗| 措美县| 津南区| 凤台县| 孟津县| 璧山县| 观塘区| 虹口区| 山东省| 泸溪县| 桂东县| 玉环县| 交口县| 潞西市| 郯城县| 德令哈市| 蓬溪县| 陆河县| 沁水县| 岑巩县| 丹阳市| 车险| 随州市|