• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[C#]AES加解密

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

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

namespace Utils
{
    /// <summary>
    /// CommonTools加密解密
    /// </summary>
    public class CommonTools
    {
        #region 加密

        static byte[] m_btIV = Convert.FromBase64String("T1hYc1BlM2hmaTVocVJLV3JOMlRrS3A4CiA=");
        static byte[] m_salt = Convert.FromBase64String("OWYya1BuMnl2SEhuQmxZUGpJRmJGMmRLOUpKTVZyOU5iR1A1RzdzZTdqWnl4WDJpc09SeFJSdzZCUjM4bHFkUQog");

        #region 加密字符串
        /// <summary>
        /// CommonTools 加密
        /// </summary>
        /// <param name="encryptString">待加密密文</param>
        /// <param name="encryptKey">加密密钥</param>
        /// <param name="encoding">编码</param>


        public static string AESEncrypt(string encryptString, string encryptKey, Encoding encoding)
        {
            if (encoding is null)
            {
                encoding = Encoding.UTF8;
            }
            return Convert.ToBase64String(AESEncrypt(encoding.GetBytes(encryptString), encryptKey));
        }
        #endregion

        #region 加密字节数组
        /// <summary>
        /// CommonTools 加密
        /// </summary>
        /// <param name="EncryptByte">待加密密文</param>
        /// <param name="encryptKey">加密密钥</param>
        public static byte[] AESEncrypt(byte[] EncryptByte, string encryptKey)
        {
            if (EncryptByte.Length == 0) { throw (new Exception("明文不得为空")); }
            if (string.IsNullOrEmpty(encryptKey)) { throw (new Exception("密钥不得为空")); }
            byte[] m_strEncrypt;
            byte[] iv = new byte[16];
            Array.Copy(m_btIV, iv, 16);


            RijndaelManaged m_AESProvider = new RijndaelManaged
            {
                // Key = keyArray,
                // IV = iv,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                BlockSize = 128
            };
            // Rijndael m_AESProvider = Rijndael.Create();
            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(encryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateEncryptor(pdb.GetBytes(32), iv);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
                m_csstream.Write(EncryptByte, 0, EncryptByte.Length);
                m_csstream.FlushFinalBlock();
                m_strEncrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strEncrypt;
        }
        #endregion
        #endregion

        #region 解密
        #region 解密字符串
        /// <summary>
        /// CommonTools 解密
        /// </summary>
        /// <param name="decryptString">待解密密文</param>
        /// <param name="decryptKey">解密密钥</param>
        /// <param name="encoding">编码</param>
        public static string AESDecrypt(string decryptString, string decryptKey, Encoding encoding)
        {
            if (encoding is null)
            {
                encoding = Encoding.UTF8;
            }
            return Convert.ToBase64String(AESDecrypt(encoding.GetBytes(decryptString), decryptKey));
        }
        #endregion

        #region 解密字节数组
        /// <summary>
        /// CommonTools 解密
        /// </summary>
        /// <param name="decryptString">待解密密文</param>
        /// <param name="decryptKey">解密密钥</param>
        public static byte[] AESDecrypt(byte[] DecryptByte, string decryptKey)
        {
            if (DecryptByte.Length == 0) { throw (new Exception("密文不得为空")); }
            if (string.IsNullOrEmpty(decryptKey)) { throw (new Exception("密钥不得为空")); }
            byte[] m_strDecrypt;
            byte[] iv = new byte[16];
            Array.Copy(m_btIV, iv, 16);

            // Rijndael m_AESProvider = Rijndael.Create();
            RijndaelManaged m_AESProvider = new RijndaelManaged
            {
                // Key = keyArray,
                // IV = iv,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                BlockSize = 128
            };

            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(decryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateDecryptor(pdb.GetBytes(32), iv);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
                m_csstream.Write(DecryptByte, 0, DecryptByte.Length);
                m_csstream.FlushFinalBlock();
                m_strDecrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strDecrypt;
        }

        public static byte[] SHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] by = Sha256.ComputeHash(SHA256Data);
            return by;
        }

        public static string Md5String(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串,
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }
        #endregion
        #endregion

    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#文件日志处理需要log4net配置发布时间:2022-07-10
下一篇:
Anders Hejlsberg谈C#、Java和C++中的泛型发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap