C# MD5加密工具类

来源:互联网 发布:淘宝店铺首页图片更换 编辑:程序博客网 时间:2024/06/02 05:14
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Util{    public class MD5    {        public static string MD5Encrypt(string str)        {            return MD5Encrypt(str, 16);        }        public static 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++)                    {                        sb.Append(hashValue[i].ToString("x2"));                    }                    break;            }            return sb.ToString();        }    }}