因为手头项目的需求,上网查了散列算法的相关信息
首先简单地运用下MD5和SHA1加密
这两重加密只需要两步,第一步引入名称空间(该名称空间也可以省略引用),第二步执行加密函数。
(1)、引入命名空间 System.Web.Security;
(2)、调用FormsAuthentication.HashPasswordForStoringInConfigFile()方法,该方法有两个参数:第一个参数是要加密的字符串;第二个参数可选值有 MD5 和 SHA1,表示使用哪种加密方法。返回加密后的字符串,注意,返回后的字符串是大写的。
如:
String md5Text = FormsAuthentication.HashPasswordForStoringInConfigFile(md5Text.Text, "MD5");
String sha1Text = FormsAuthentication.HashPasswordForStoringInConfigFile(sha1Text.Text, "SHA1");
以下是用散列算法进行加密,可以用MD5和SHA1,先要引入命名空间 System.Security.Cryptography;
string plaintext = TextBox3.Text.ToString(); ;
byte[] srcBuffer = System.Text.Encoding.UTF8.GetBytes(plaintext);
//HashAlgorithm hash = HashAlgorithm.Create("SHA1");
HashAlgorithm hash = HashAlgorithm.Create("MD5");
byte[] destBuffer = hash.ComputeHash(srcBuffer);
Label4.Text = BitConverter.ToString(destBuffer).Replace("-", "");
用的是 HashAlgorithm 这个类,只用了它的两个方法:Create 和 ComputeHash,ComputeHash 返回的是 byte[],为了显示这里转换成字符串,转换之后,返回后的字符串是大写的。
也可以用 SHA1Managed 和 SHA1CryptoServiceProvider,但是我们推荐用本文的方法,因为它不涉及类名,要更改算法,只需要更改 Create 的字符串参数即可,如:MD5。