- C# 加密-MD5 和 SHA1
- C# 加密-散列算法
- C# 加密-RSA
- C# 加密-RSA 高级
- C# 加密-TripleDES
- C# 加密-Rijndael
- C# 加密-密钥容器
- C# 加密-Managed 与 Provider
创建散列码的方法非常多,即使是同一种散列算法也可以通过许多类来实现,前面章节介绍的算一种,下面再介绍一种。以 SHA1 为例:
string plaintext = "明文";
byte[] srcBuffer = System.Text.Encoding.UTF8.GetBytes(plaintext);
HashAlgorithm hash = HashAlgorithm.Create("SHA1");
byte[] destBuffer = hash.ComputeHash(srcBuffer);
string hashedText = BitConverter.ToString(destBuffer).Replace("-", "");
byte[] srcBuffer = System.Text.Encoding.UTF8.GetBytes(plaintext);
HashAlgorithm hash = HashAlgorithm.Create("SHA1");
byte[] destBuffer = hash.ComputeHash(srcBuffer);
string hashedText = BitConverter.ToString(destBuffer).Replace("-", "");
用的是 HashAlgorithm 这个类,只用了它的两个方法:Create 和 ComputeHash,ComputeHash 返回的是 byte[],为了显示这里转换成字符串,转换之后,它和前一节讲的 SHA1 结果是一样的。
也可以用 SHA1Managed 和 SHA1CryptoServiceProvider,但是我们推荐用本文的方法,因为它不涉及类名,要更改算法,只需要更改 Create 的字符串参数即可。
相关阅读
