C# 中AES 加密和解密通用方法

AES密码编写

​要编写AES算法,首先了解AES算法原理,AES算法是一个对称分组密码算法。数据分组长度必须是 128 bits,使用的密钥长度为 128,192 或 256 bits。对于三种不同密钥长度的 AES 算法,分别称为“AES-128”、“AES-192”、“AES-256”。AES加密算法涉及4种操作:字节替代(SubBytes)、行移位(ShiftRows)、列混(MixColumns)和轮密钥加(AddRoundKey)。

​ 从AES的加密和解密的流程图中可知:解密算法的每一步分别对应加密算法的逆操作。加解密所有操作的顺序正好是相反的,正是这样才保证了算法的正确性。加解密中每轮的密钥分别由种子密钥经过密钥扩展算法得到,算法中16字节的明文、密文和轮子密钥都以一个4x4的矩阵表示。

下面提供一种C#方式实现的工具类:

  /// <summary>
    /// AES加解密字符串
    /// </summary>
    public static class AESCryptoTextProvider
    {
        #region 方法

        /// <summary>
        /// 加密
        /// IV等于Key且Key和IV将被转换为MD5值
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="sourceText">原文</param>
        /// <returns>密文(Base64字符串)</returns>
        public static string Encrypt(string key, string sourceText)
        {
            return Encrypt(key, key, sourceText);
        }

        /// <summary>
        /// 加密
        /// Key和IV将被转换为MD5值
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="IV">初始化向量</param>
        /// <param name="sourceText">原文</param>
        /// <returns>密文(Base64字符串)</returns>
        public static string Encrypt(string key, string IV, string sourceText)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (IV == null)
                throw new ArgumentNullException(nameof(IV));
            if (sourceText == null)
                throw new ArgumentNullException(nameof(sourceText));

            using (SHA512 sha512 = SHA512.Create())
            {
                return Convert.ToBase64String(Encrypt(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key)), sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(IV)), sourceText));
            }
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="rgbKey">密钥</param>
        /// <param name="rgbIV">初始化向量</param>
        /// <param name="sourceText">原文</param>
        /// <returns>密文</returns>
        public static byte[] Encrypt(byte[] rgbKey, byte[] rgbIV, string sourceText)
        {
            if (rgbKey == null)
                throw new ArgumentNullException(nameof(rgbKey));
            if (rgbIV == null)
                throw new ArgumentNullException(nameof(rgbIV));
            if (sourceText == null)
                throw new ArgumentNullException(nameof(sourceText));

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Aes aes = Aes.Create())
                using (ICryptoTransform transform = aes.CreateEncryptor(rgbKey, rgbIV))
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
                using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                {
                    streamWriter.Write(sourceText);
                    streamWriter.Flush();
                }

                return memoryStream.ToArray();
            }
        }

        /// <summary>
        /// 解密
        /// IV等于Key且Key和IV将被转换为MD5值
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="cipherText">密文(Base64字符串)</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, string cipherText)
        {
            return Decrypt(key, key, cipherText);
        }

        /// <summary>
        /// 解密
        /// Key和IV将被转换为MD5值
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="IV">初始化向量</param>
        /// <param name="cipherText">密文(Base64字符串)</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, string IV, string cipherText)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (IV == null)
                throw new ArgumentNullException(nameof(IV));
            if (cipherText == null)
                throw new ArgumentNullException(nameof(cipherText));

            using (SHA512 sha512 = SHA512.Create())
            {
                return Decrypt(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key)), sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(IV)), Convert.FromBase64String(cipherText));
            }
        }

        /// <summary>
        /// 解密
        /// IV等于Key
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="cipherBuffer">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, byte[] cipherBuffer)
        {
            return Decrypt(key, key, cipherBuffer);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="IV">初始化向量</param>
        /// <param name="cipherBuffer">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, string IV, byte[] cipherBuffer)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (IV == null)
                throw new ArgumentNullException(nameof(IV));
            if (cipherBuffer == null)
                throw new ArgumentNullException(nameof(cipherBuffer));

            using (SHA512 sha512 = SHA512.Create())
            {
                return Decrypt(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key)), sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(IV)), cipherBuffer);
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="rgbKey">密钥</param>
        /// <param name="rgbIV">初始化向量</param>
        /// <param name="cipherBuffer">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(byte[] rgbKey, byte[] rgbIV, byte[] cipherBuffer)
        {
            if (rgbKey == null)
                throw new ArgumentNullException(nameof(rgbKey));
            if (rgbIV == null)
                throw new ArgumentNullException(nameof(rgbIV));
            if (cipherBuffer == null)
                throw new ArgumentNullException(nameof(cipherBuffer));

            using (MemoryStream stream = new MemoryStream(cipherBuffer))
            {
                return Decrypt(rgbKey, rgbIV, stream);
            }
        }

        /// <summary>
        /// 解密
        /// IV等于Key
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="cipherStream">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, Stream cipherStream)
        {
            return Decrypt(key, key, cipherStream);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="IV">初始化向量</param>
        /// <param name="cipherStream">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(string key, string IV, Stream cipherStream)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (IV == null)
                throw new ArgumentNullException(nameof(IV));
            if (cipherStream == null)
                throw new ArgumentNullException(nameof(cipherStream));

            using (SHA512 sha512 = SHA512.Create())
            {
                return Decrypt(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key)), sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(IV)), cipherStream);
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="rgbKey">密钥</param>
        /// <param name="rgbIV">初始化向量</param>
        /// <param name="cipherStream">密文</param>
        /// <returns>原文</returns>
        public static string Decrypt(byte[] rgbKey, byte[] rgbIV, Stream cipherStream)
        {
            if (rgbKey == null)
                throw new ArgumentNullException(nameof(rgbKey));
            if (rgbIV == null)
                throw new ArgumentNullException(nameof(rgbIV));
            if (cipherStream == null)
                throw new ArgumentNullException(nameof(cipherStream));

            using (Aes aes = Aes.Create())
            using (ICryptoTransform transform = aes.CreateDecryptor(rgbKey, rgbIV))
            using (CryptoStream cryptoStream = new CryptoStream(cipherStream, transform, CryptoStreamMode.Read))
            using (StreamReader streamReader = new StreamReader(cryptoStream))
            {
                return streamReader.ReadToEnd();
            }
        }

        #endregion
    }
  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
首先,需要引入System.Security.Cryptography命名空间。 以下是C#窗体实现AES加密解密的示例代码: ``` using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace AesDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnEncrypt_Click(object sender, EventArgs e) { try { // 获取密钥和向量 string key = txtKey.Text.Trim(); string iv = txtIV.Text.Trim(); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); // 获取明文 string plaintext = txtPlaintext.Text.Trim(); byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); // 创建AES加密器 using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; // 创建加密流 using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write)) { // 将明文写入加密流 csEncrypt.Write(plaintextBytes, 0, plaintextBytes.Length); csEncrypt.FlushFinalBlock(); // 获取加密结果 byte[] ciphertextBytes = msEncrypt.ToArray(); string ciphertext = Convert.ToBase64String(ciphertextBytes); // 显示加密结果 txtCiphertext.Text = ciphertext; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnDecrypt_Click(object sender, EventArgs e) { try { // 获取密钥和向量 string key = txtKey.Text.Trim(); string iv = txtIV.Text.Trim(); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); // 获取密文 string ciphertext = txtCiphertext.Text.Trim(); byte[] ciphertextBytes = Convert.FromBase64String(ciphertext); // 创建AES解密器 using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; // 创建解密流 using (MemoryStream msDecrypt = new MemoryStream(ciphertextBytes)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, aes.CreateDecryptor(), CryptoStreamMode.Read)) { // 读取解密结果 byte[] plaintextBytes = new byte[ciphertextBytes.Length]; int bytesRead = csDecrypt.Read(plaintextBytes, 0, plaintextBytes.Length); // 显示解密结果 string plaintext = Encoding.UTF8.GetString(plaintextBytes, 0, bytesRead); txtPlaintext.Text = plaintext; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } ``` 在窗体上添加三个TextBox控件和两个Button控件,分别命名为txtKey、txtIV、txtPlaintext、txtCiphertext、btnEncrypt和btnDecrypt。用户输入密钥、向量和明文,点击“加密”按钮进行加密,点击“解密”按钮进行解密加密解密过程,采用AES算法进行加密解密,使用Base64编码将密文转换为字符串。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天hous

你的鼓励是我最大动力~谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值