MD5加密,web和winform
Web
/// <summary> /// 获取获取MD5加密后字符串 /// </summary> /// <param name="sourceString">源字符串</param> /// <param name="digits">加密位数(16或32)</param> /// <param name="isToUpper">是否大写</param> /// <returns></returns> public static string Md5Encode(string sourceString, int digits, bool isToUpper) { if (string.IsNullOrEmpty(sourceString)) return string.Empty; var targetString = digits == 16 ? System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( sourceString, "MD5").Substring(8, 16) : System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( sourceString, "MD5"); if (targetString != null) return isToUpper ? targetString.ToUpper() : targetString.ToLower(); return null; }
Winform
/// <summary> /// 加密 /// </summary> /// <param name="source">加密字符串</param> /// <returns></returns> private string MD5(string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(source)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < encryptedBytes.Length; i++) { sb.AppendFormat("{0:X2}", encryptedBytes[i]); } return sb.ToString(); }
16位:截取8到16位,Substring(8, 16)