.net如何对字符串进行md5或sha1加密?

如题所述

string text1 = "123456";

//方法1:引用了System.Web程序集的使用方法。
string md5Result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( text1, "MD5" );
string sha1Result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( text1, "SHA1" );

//方法2:未引用System.Web
byte[] text1Bytes = System.Text.Encoding.UTF8.GetBytes( text1 );
MD5 md5 = MD5.Create();
byte[] md5Bytes = md5.ComputeHash( text1Bytes );
StringBuilder md5ResultBuilder = new StringBuilder( 32 );
for ( int i = 0; i < md5Bytes.Length; i++ )
{
md5ResultBuilder.AppendFormat( "{0:X2}", md5Bytes[ i ] );
}
string md5Result1 = md5ResultBuilder.ToString();

SHA1 sha1 = SHA1.Create();
byte[] sha1Bytes = sha1.ComputeHash( text1Bytes );
StringBuilder sha1ResultBuilder = new StringBuilder( 40 );
for ( int i = 0; i < sha1Bytes.Length; i++ )
{
sha1ResultBuilder.AppendFormat( "{0:X2}", sha1Bytes[ i ] );
}
string sha1Result1 = sha1ResultBuilder.ToString();

PS:Encoding 的命名空间是 System.Text
MD5和SHA1的命名空间是System.Security.Cryptography

MD5加密结果是 128位,即16字节,转换成字符串,就是32个字符。
SHA加密结果是 160位,即20字节,转换成字符串,就是40个字符。
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2016-10-06
比如:对字符ss加密.
Strin ss="8888";
Strin pp=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(ss, "md5")

输出pp就是加密过的.本回答被提问者采纳
第2个回答  2008-08-31
HTML,CSS,C#基本概念都懂
相似回答