asp.net

asp.net aes加密如何实现

小樊
82
2024-12-04 23:49:20
栏目: 编程语言

在ASP.NET中实现AES加密,你可以使用System.Security.Cryptography命名空间中的类。以下是一个简单的示例,展示了如何使用AES加密和解密字符串。

首先,确保已经安装了System.Security.Cryptography NuGet包。

然后,创建一个名为AesEncryptionHelper的类,用于封装加密和解密方法:

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

public static class AesEncryptionHelper
{
    private static readonly byte[] Key = Encoding.UTF8.GetBytes("your-secret-key"); // 替换为你的密钥
    private static readonly byte[] IV = Encoding.UTF8.GetBytes("your-initial-vector"); // 替换为你的初始向量

    public static string Encrypt(string plainText)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            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);
                    }
                }

                return Convert.ToBase64String(ms.ToArray());
            }
        }
    }

    public static string Decrypt(string cipherText)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

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

            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(cipherText)))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }
    }
}

现在,你可以在你的ASP.NET应用程序中使用AesEncryptionHelper类来加密和解密字符串。例如:

protected void Page_Load(object sender, EventArgs e)
{
    string plainText = "Hello, World!";
    string encryptedText = AesEncryptionHelper.Encrypt(plainText);
    string decryptedText = AesEncryptionHelper.Decrypt(encryptedText);

    // 输出加密后的字符串
    Response.Write("Encrypted Text: " + encryptedText);

    // 输出解密后的字符串
    Response.Write("Decrypted Text: " + decryptedText);
}

请注意,你需要将your-secret-keyyour-initial-vector替换为你自己的密钥和初始向量。密钥和初始向量的长度应根据所使用的AES加密模式进行调整。例如,对于AES-256,密钥长度应为32字节,初始向量长度应为16字节。

0
看了该问题的人还看了