各种加密算法

md5:


       /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string MD5(string str, Encoding encoding)
        {
            byte[] b = encoding.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

调用方法:
//  必须制定编码,c#默认是gb2132,但java等语言是utf-8,所以尽量通用
XXX.Common.Encrypt.MD5(strPrepare,Encoding.UTF8);

 


 

Hmac_MD5:

    private string Hmac_MD5(string key,string message)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(key);
            HMACMD5 hmacmd5 = new HMACMD5(keyByte);
            byte[] messageBytes = encoding.GetBytes(message);
            byte[] hashmessage = hmacmd5.ComputeHash(messageBytes);
            string rtnVal = ByteToString(hashmessage);
            return rtnVal.ToLower();
        }

        private static string ByteToString(byte[] buff)
        {
            string sbinary = "";
            for (int i = 0; i < buff.Length; i++)
            {
                sbinary += buff[i].ToString("X2"); 
            }
            return (sbinary);
        }

Hmac_SHA1加密:

/// <summary>
        /// HmacSHA1方式进行macmacmac签名
        /// </summary>
        /// <param name="text">加密的内容</param>
        /// <param name="key">加密key</param>
        /// <returns></returns>
        public string HmacSha1(string text, string key)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = Encoding.UTF8.GetBytes(key);
            byte[] dataBuffer = Encoding.UTF8.GetBytes(text);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }

 

posted @ 2015-02-16 19:33  沙漠绿洲uibe  阅读(224)  评论(0编辑  收藏  举报