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

    }
}

 

posted on 2020-03-26 11:04  凌度  阅读(456)  评论(0编辑  收藏  举报