基础分享C#封装的几个加解密类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基础分享C#封装的几个加解密类相关的知识,希望对你有一定的参考价值。

前段时间一个业余项目涉及到字符串和文件的加密,所以写了封装了几个给予DES,AES,MD5的加密解密类.

直接看代码

DesSecurity.cs

 

技术分享
/// <summary>
    /// 基于DES加密解密
    /// </summary>
    public static class DesSecurity
    {
        public static byte[] Encrypt( byte[] data  ,string key , bool ispaddingzeros = true, bool isEcbMode = true )
        {
            byte[] result;
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider
            {
                Key = Encoding.Default.GetBytes(key),
                IV = Encoding.Default.GetBytes("visonsec"),
                Mode = isEcbMode ? CipherMode.ECB : CipherMode.CBC,
                Padding = ispaddingzeros ? PaddingMode.Zeros : PaddingMode.None
            })
            {
                byte[] array;
                using(MemoryStream ms  = new MemoryStream())
                {
                    using(CryptoStream cryptoStream = new CryptoStream( ms , des.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(data, 0, data.Length);
                        cryptoStream.FlushFinalBlock();
                    }

                    array = ms.ToArray();
                }

                result = array;
            }

            return result;
        }

        public static string Encrypt( string data, string key )
        {
            byte[] bytes = Encoding.Default.GetBytes(data);
            byte[] valuetocon = DesSecurity.Encrypt(bytes , key, true ,true );

            return StringConverter.ToHexString(valuetocon);
        }

        public static byte[] Descrypt( byte[] data ,string key , bool ispaddingzeros  = true , bool isecbmode = true )
        {
            byte[] result;
            using(DESCryptoServiceProvider des = new DESCryptoServiceProvider{
                Key = Encoding.Default.GetBytes(key),
                IV = Encoding.Default.GetBytes("visonsec"),
                Mode= isecbmode ? CipherMode.ECB : CipherMode.CBC ,
                Padding = ispaddingzeros ? PaddingMode.Zeros:PaddingMode.None
            })
            {
                byte[] array;
                using (MemoryStream ms = new MemoryStream())
                {
                    using( CryptoStream cs = new CryptoStream( ms , des.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                    }
                    array = ms.ToArray();
                }
                result = array;
            }

            return result;
        }

        public static string Descrypt(string data , string key )
        {
            byte[] datas = StringConverter.ToHexBytes(data);
            byte[] bytes = DesSecurity.Descrypt(datas, key, true, true);
            return Encoding.Default.GetString(bytes).Replace("\0", null);
        }
    }
View Code

 

AESSecurity.cs

 

技术分享
public static class  AESSecurity
    {
        public static byte[] Encrypt(byte[] data, string key)
        {
            Rijndael rijndael = Rijndael.Create();
            rijndael.Mode = CipherMode.ECB;
            rijndael.Padding = PaddingMode.PKCS7;
            rijndael.Key = Encoding.UTF8.GetBytes(key);
            byte[] result;
            try
            {
                using(MemoryStream ms = new MemoryStream())
                {
                    using(CryptoStream cs = new CryptoStream(ms,rijndael.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                        result = ms.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("AES EXCEPTION:" + ex.Message);
                result = null; 
            }
            finally
            {
                rijndael.Clear();
            }

            return result;
        }

        public static byte[] Encrypt(string data, string key) {
            return AESSecurity.Encrypt(Encoding.UTF8.GetBytes(data), key);
        }

        public static byte[] Descrypt(byte[] data ,string key )
        {
            Rijndael rijndael = Rijndael.Create();
            rijndael.Mode = CipherMode.ECB;
            rijndael.Padding = PaddingMode.PKCS7;
            rijndael.Key = Encoding.UTF8.GetBytes(key);
            byte[] result;
            try
            {
                using(MemoryStream ms = new MemoryStream())
                {
                    using(CryptoStream cs = new CryptoStream(ms, rijndael.CreateDecryptor() , CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                        result = ms.ToArray();
                    }
                }
            }
            catch (Exception e)
            {
                result = null;
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            finally
            {
                rijndael.Clear();
            }

            return result;
        }
    }
View Code

MD5Security.cs

技术分享
            byte[] buf = StringConverter.ToBytes(value);
            string result;
            using(MD5CryptoServiceProvider md = new MD5CryptoServiceProvider())
            {
                byte[] v = md.ComputeHash(buf);
                string s = BitConverter.ToString(v, 4, 8).Replace("-", string.Empty);
                result = s;
            }

            return result;
        }

        public static string Encrypt32( string value )
        {
            if (value == null) throw new ArgumentNullException("value");
            byte[] buf = StringConverter.ToBytes(value);
            string result = null;
            using(MD5CryptoServiceProvider md = new MD5CryptoServiceProvider())
            {
                byte[] array = md.ComputeHash(buf);
                StringBuilder sb = new StringBuilder();
                for(int i = 0 ; i < array.Length ; i++ )
                {
                    sb.Append(array[i].ToString("x2"));
                }
                result = sb.ToString();
            }

            return result;
        }

        public static string GetMD5FromFile( string file )
        {
            if(File.Exists(file))
            {
                string result;
                using(FileStream fs = new FileStream(file,FileMode.Open))
                {
                    using(MD5CryptoServiceProvider md = new MD5CryptoServiceProvider())
                    {
                        byte[] array = md.ComputeHash(fs);
                        StringBuilder sb = new StringBuilder();
                        for( int i = 0 ;  i < array.Length ; i++ )
                        {
                            sb.Append(array[i].ToString("x2"));
                        }
                        result = sb.ToString();
                    }
                }

                return result;
            }
            else
            {
                return null;
            }
        }
    }
View Code

StringConverter.cs 字符串转换辅助类

 

技术分享
 [System.Flags]
    public enum StringEncodeType
    {
        EN_Default = 0 ,
        EN_UTF8 = 1 ,
        EN_UnicodeEncoding  = 2 ,
        EN_Base64 = 3
    }
    public static class StringConverter
    {
        public static string ToHexString(byte[] valueToConvert)
        {
            if (valueToConvert == null)
            {
                throw new ArgumentNullException();
            }
            string text = string.Empty;
            for (int i = 0; i < valueToConvert.Length; i++)
            {
                text += valueToConvert[i].ToString("X2");
            }
            return text;
        }
        public static byte[] ToHexBytes(string valueToConvert)
        {
            if (valueToConvert == null)
            {
                throw new ArgumentNullException("valueToConvert");
            }
            valueToConvert = valueToConvert.Replace(" ", string.Empty);
            if (valueToConvert.Length % 2 != 0)
            {
                throw new FormatException("valueToConvert");
            }
            byte[] array = new byte[valueToConvert.Length / 2];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = Convert.ToByte(valueToConvert.Substring(i * 2, 2), 16);
            }
            return array;
        }

        public static byte[] ToBytes(string valueToConvert, StringEncodeType stringEncodingType)
        {
            if (valueToConvert == null)
            {
                throw new ArgumentNullException("valueToConvert");
            }
            byte[] result = null;
            switch (stringEncodingType)
            {
                case StringEncodeType.EN_Default:
                    result = Encoding.Default.GetBytes(valueToConvert);
                    break;
                case StringEncodeType.EN_UTF8:
                    result = Encoding.UTF8.GetBytes(valueToConvert);
                    break;
                case StringEncodeType.EN_UnicodeEncoding:
                    result = new UnicodeEncoding().GetBytes(valueToConvert);
                    break;
                case StringEncodeType.EN_Base64:
                    result = Convert.FromBase64String(valueToConvert);
                    break;
            }
            return result;
        }

        public static byte[] ToBytes(string valueToConvert)
        {
            return StringConverter.ToBytes(valueToConvert, StringEncodeType.EN_UTF8);
        }

    }
View Code

 

 

--------

   end 

 

以上是关于基础分享C#封装的几个加解密类的主要内容,如果未能解决你的问题,请参考以下文章

常用的几个JQuery代码片段

减少前端代码耦合的几个方法

C#编程开发的几个基础小知识

个人一些小工具类库分享

Spring AOP中的几个概念

分享Java面试中的几个重要基础问题