1. 程式人生 > >c# 中的MD5和sha1加密

c# 中的MD5和sha1加密

下面列出c#中MD5加密和sha1加密的方法,以供參考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace MD5.Helper
{
    public static class EncryptHelper
    {

        /// <summary>
        /// MD5加密:
        /// 16位小寫
/// 16位大寫 /// 32位小寫 /// 32位大寫 /// </summary> /// <param name="strText"></param> /// <param name="type"></param> /// <returns></returns> public static string GetMD5(string strText,MD5Type type) { string
strReturn = string.Empty; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(strText)); if (type == MD5Type.Bit16Lower) { strReturn = BitConverter.ToString(result, 4
, 8).Replace("-", string.Empty).ToLower(); } if (type == MD5Type.Bit16Upper) { strReturn = BitConverter.ToString(result, 4, 8).Replace("-", string.Empty).ToUpper(); } if (type == MD5Type.Bit32Lower) { strReturn = BitConverter.ToString(result).Replace("-", string.Empty).ToLower(); } if (type == MD5Type.Bit32Upper) { strReturn = BitConverter.ToString(result).Replace("-", string.Empty).ToUpper(); } return strReturn; } /// <summary> /// Base64加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetBase64(string str) { byte[] strArray = Encoding.Default.GetBytes(str); return Convert.ToBase64String(strArray); } /// <summary> /// sha1加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetSha1(string str) { var buffer = Encoding.UTF8.GetBytes(str); var data = SHA1.Create().ComputeHash(buffer); string result= BitConverter.ToString(data).Replace("-",string.Empty).ToLower(); return result; } } public enum MD5Type { Bit16Upper,//16位大寫 Bit16Lower,//16位小寫 Bit32Upper,//32位大寫 Bit32Lower,//32位小寫 } }