AES-256-CBC 加密解密

 //AES加密/解密
        //在线AES加密解密工具。
        //            AES采用对称分组密码体制,
        //            密钥长度支持为128/192/256bits。
        //            用户密钥长度不足时,平台将以0x00自动填充。
        //            IV也一样,自动填充,超出部分将被忽略。
        //            加密时会将明文数据按16byte进行分组,
        //            不足16byte时将用特定的Padding(如PCKS7)字符进填充,
        //            所以不同的Padding方式密文最后一段可能不一样。
        //            如果没有特别指明平台将使用UTF8编码处理数据(如KEY/IV)。

测试网站
        //https://the-x.cn/cryptography/Aes.aspx

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AesEncrypt
{
    /// <summary>
    /// Aes扩展方法
    /// </summary>
    public class AesEncryptExtension
    {
        public CipherMode Mode { get; internal set; }
        public PaddingMode Padding { get; internal set; }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text">被加密的字符串</param>
        /// <param name="aesKey">对称算法的密钥</param>
        /// <param name="aesIV">设置对称算法的初始化向量</param>
        /// <returns>Base64</returns>
        public string Encrypt(string Text, byte[] aesKey, byte[] aesIV)
        {
            byte[] encrypted;
            encrypted = EncryptStringToBytes_Aes(Text, aesKey, aesIV);
            return Convert.ToBase64String(encrypted);
        }
        private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
           // using (RijndaelManaged aesAlg = new RijndaelManaged())

          using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                //設定 cipher 格式 AES-256-CBC
                //aesAlg.BlockSize = 256;
                //aesAlg.KeySize = 128;
                //aesAlg.FeedbackSize = 128;
                aesAlg.Padding = PaddingMode.PKCS7;
                aesAlg.Mode = CipherMode.CBC;

                //aesAlg.Key = (new SHA256Managed()).ComputeHash(Encoding.ASCII.GetBytes("IHazSekretKey"));
                //aesAlg.IV = System.Text.Encoding.ASCII.GetBytes("1234567890123456");
                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        //csEncrypt.FlushFinalBlock();
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="text">被Aes加密后的Base64</param>
        /// <param name="aesKey">对称算法的密钥</param>
        /// <param name="aesIV">设置对称算法的初始化向量</param>
        /// <returns>字符串</returns>
        public string Decrypt(string text, byte[] aesKey, byte[] aesIV)
        {
            string roundtrip;

            byte[] myByte = Convert.FromBase64String(text);
            roundtrip = DecryptStringFromBytes_Aes(myByte, aesKey, aesIV);

            return roundtrip;
        }
        private string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }
            // Declare the string used to hold
            // the decrypted text.
            string plaintext;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return plaintext;
        }

    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值