日期:2011-06-11  浏览次数:20611 次

网上流行的asp版md5.perl版des算法在C#中的简单实现


1:MD5

以前在asp时代常用的MD5算法好象是从动网流出来的,后来大家都用它,基本上有两种 ,区别在md5.asp的结尾部分

MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
 
MD5=LCase(WordToHex(b) & WordToHex(c)) 

分别对应32位和16位加密方式

在C#中对应的实现为

/// <summary>
       /// 16位MD5加密方法,以前的DVBBS所使用
       /// </summary>
       /// <param name="strSource">待加密字串</param>
        /// <returns>加密后的字串</returns>
        public string MD5Encrypt(string strSource)
        {
            return MD5Encrypt(strSource, 16);
        }
        /// <summary>
        /// MD5加密,和动网上的16/32位MD5加密结果相同
        /// </summary>
        /// <param name="strSource">待加密字串</param>
        /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
        /// <returns>加密后的字串</returns>
        public string MD5Encrypt(string strSource, int length)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(strSource);
            byte[] hashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            switch (length)
            {
                case 16:
                    for (int i = 4; i < 12; i++)
                        sb.Append(hashValue[i].ToString("x2"));
                    break;
                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                default:
                    for (int i = 0; i < hashValue.Length; i++)
             &nb