SHA1哈希算法是一个用来进行数字签名的算法,对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要,这个消息摘要可以用来验证数据的完整性。SHA1有一些特性,一是不可以从消息摘要中复原信息,另外一个就是不同的消息会产生不同的消息摘要。所以如果在传输的过程中,数据发生了丢失或者损坏,通过消息摘要就可以看出来。
在.NET中对程序集进行强签名的时候,需要生成一个公钥,通过公钥生成一个公钥标记的时候也会用到SHA1算法。这个算法的具体原理,可以在网上找到,这里介绍一下用.NET提供的类库来使用这个算法。主要有四种使用方式。
1.通过SHA1CryptoServiceProvider
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
//strSource为传入的字符串,字节数组为加密后的
byte[] bytResult = sha.ComputeHash(System.Text.Encoding.Default.GetBytes(strSource));
2.通过SHA1类
System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
//注意编码UTF8、UTF7、Unicode等的选择
byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));
3.通过HashPasswordForStoringInConfigFile方法
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "SHA1");
4.使用SHA1Managed
SHA1Managed sha = new SHA1Managed();
byte[] bytResult = sha.ComputeHash(strSource);
四种方法生成的结果都一样,唯一需要注意的就是传入的字符串的编码。