MD5加密的绵集

using System;
using System.Security;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Web;
using System.Text;

namespace Bigeagle.Util
{
   
    /// <summary>
    /// 一个加密类
    /// <br>Author:  Bigeagle@163.net</br>
    /// <br>Date:    2001/09/25</br>
    /// <br>History: 2001/10/25 finished</br>
    /// </summary>
    /// <remarks>
    /// 封装常用的加密算法
    /// </remarks>
    public class Cryptography
    {
        /// <summary>
        /// 生成16位随机密码
        /// </summary>
        /// <returns></returns>
        public static string createpass()
        {
            int Ran, LengthNum = 16;
            string Createpass = "";
            for (int i = 1; i < LengthNum; i++)
            {
                Random ram = new Random();
                Ran = Convert.ToInt32(ram.NextDouble() * 2);
                if (Ran == 0)
                {
                    Ran = Convert.ToInt32(ram.NextDouble() * 25) + 97;
                    Createpass = Createpass + Convert.ToString(Convert.ToChar(Ran)).ToUpper();
                }
                else if (Ran == 1)
                {
                    Ran = Convert.ToInt32(ram.NextDouble() * 9);
                    Createpass = Createpass + Ran;
                }
                else if (Ran == 2)
                {
                    Ran = Convert.ToInt32(ram.NextDouble() * 25) + 97;
                    Createpass = Createpass + Convert.ToString(Convert.ToChar(Ran));
                }
            }
            return Createpass;
        }
        static void Main(string[] args)
        {
            string s = Encrypt3DES("Study", "fonny");
           Console.WriteLine(s);
            Console.WriteLine(Decrypt3DES(s,"fonny"));
            Console.WriteLine(CalculateMD5Hash("Study"));
            Console.WriteLine(GetMD5("Study","gb2312"));
            Console.WriteLine(createpass());
        }

        /// <summary>
        /// md5加密指定字符串
        /// </summary>
        /// <param name="a_strValue">要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string EncryptMD5String(string a_strValue)
        {
#if DEBUG
            Debug.Assert(a_strValue.Trim() != "", "空字符串", "空字符串不需要加密");
#endif//DEBUG

            //转换成bytearray
            Byte[] hba = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).
                        ComputeHash(StringToByteArray(a_strValue));

            return ByteArrayToString(hba);
        }

        /// <summary>
        /// md5(1)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();

            //这个是C#中的,web中的FormsAuthentication.HashPasswordForStoringInConfigFile(字符串,"MD5")也可以实现

        }
        /// <summary>
        /// md5(2)
        /// </summary>
        /// <param name="s"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetMD5(string s, string encoding)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(encoding).GetBytes(s));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString().ToLower();
        }


        /// <summary>
        /// 判断两个加密字符串是否相同
        /// </summary>
        /// <param name="a_str1"></param>
        /// <param name="a_str2"></param>
        /// <returns>如果相同返回真</returns>
        public static bool IsSame(string a_str1, string a_str2)
        {
            Byte[] b1 = StringToByteArray(a_str1);
            Byte[] b2 = StringToByteArray(a_str2);
            if (b1.Length != b2.Length)
            {
                return false;
            }

            for (int i = 0; i < b1.Length; i++)
            {
                if (b1[i] != b2[i])
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 转换string到Byte树组
        /// </summary>
        /// <param name="s">要转换的字符串</param>
        /// <returns>转换的Byte数组</returns>
        public static Byte[] StringToByteArray(String s)
        {
            /*
            Char[] ca = s.ToCharArray();
            Byte[] ba = new Byte[ca.Length];
            for(int i=0; i<ba.Length; i++) ba[i] = (Byte)ca[i];
            return ba;*/

            return Encoding.UTF8.GetBytes(s);
        }

        /// <summary>
        /// 转换Byte数组到字符串
        /// </summary>
        /// <param name="a_arrByte">Byte数组</param>
        /// <returns>字符串</returns>
        public static string ByteArrayToString(Byte[] a_arrByte)
        {
            /*
            //char[] ca = new char[a_arrByte.Length] ;
            for(int i = 0 ; i < a_arrByte.Length ; i ++)
            {
                result += (char)a_arrByte[i] ;
            }*/

            return Encoding.UTF8.GetString(a_arrByte);
        }


        /// <summary>
        /// 3des加密字符串
        /// </summary>
        /// <param name="a_strString">要加密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <returns>加密后并经base64编码的字符串</returns>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Encrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
                (Buffer, 0, Buffer.Length));
        }//end method

        /// <summary>
        /// 3des加密字符串
        /// </summary>
        /// <param name="a_strString">要加密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>加密后并经base63编码的字符串</returns>
        /// <remarks>重载,指定编码方式</remarks>
        public static string Encrypt3DES(string a_strString, string a_strKey, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = encoding.GetBytes(a_strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
                (Buffer, 0, Buffer.Length));
        }


        /// <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="a_strString">要解密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <returns>解密后的字符串</returns>
        /// <exception cref="">密钥错误</exception>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Decrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(a_strString);
                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock
                    (Buffer, 0, Buffer.Length));
            }
            catch (Exception e)
            {
#if DEBUG
                Console.WriteLine("错误:{0}", e);
#endif//DEBUG
                throw (new Exception("Invalid Key or input string is not a valid base64 string", e));
            }

            return result;
        }//end method

        /// <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="a_strString">要解密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>解密后的字符串</returns>
        /// <exception cref="">密钥错误</exception>
        /// <remarks>静态方法,指定编码方式</remarks>
        public static string Decrypt3DES(string a_strString, string a_strKey, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(a_strString);
                result = encoding.GetString(DESDecrypt.TransformFinalBlock
                    (Buffer, 0, Buffer.Length));
            }
            catch (Exception e)
            {
#if DEBUG
                Console.WriteLine("错误:{0}", e);
#endif//DEBUG
                throw (new Exception("Invalid Key or input string is not a valid base64 string", e));
            }

            return result;
        }//end method


    }
}

posted @ 2008-03-29 22:47  花香的蜂  阅读(658)  评论(1编辑  收藏  举报