Bouncy Castle是一个流行的加密库,提供了许多加密算法,包括哈希算法。在C#中,你可以使用Bouncy Castle库来实现各种哈希算法。以下是一些常见的哈希算法及其在Bouncy Castle中的实现:
- SHA-1:
using System; using System.Security.Cryptography; using org.bouncycastle.crypto.digests; using org.bouncycastle.crypto.hash; using org.bouncycastle.crypto.Macs; using org.bouncycastle.crypto.engines; public class SHA1Example { public static void Main() { byte[] data = https://www.yisu.com/ask/Encoding.UTF8.GetBytes("Hello, World!"); IHash digest = new SHA1Digest(); digest.Update(data, 0, data.Length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "")); } }
- SHA-256:
using System; using System.Security.Cryptography; using org.bouncycastle.crypto.digests; using org.bouncycastle.crypto.hash; public class SHA256Example { public static void Main() { byte[] data = https://www.yisu.com/ask/Encoding.UTF8.GetBytes("Hello, World!"); IHash digest = new SHA256Digest(); digest.Update(data, 0, data.Length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "")); } }
- SHA-384:
using System; using System.Security.Cryptography; using org.bouncycastle.crypto.digests; using org.bouncycastle.crypto.hash; public class SHA384Example { public static void Main() { byte[] data = https://www.yisu.com/ask/Encoding.UTF8.GetBytes("Hello, World!"); IHash digest = new SHA384Digest(); digest.Update(data, 0, data.Length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "")); } }
- SHA-512:
using System; using System.Security.Cryptography; using org.bouncycastle.crypto.digests; using org.bouncycastle.crypto.hash; public class SHA512Example { public static void Main() { byte[] data = https://www.yisu.com/ask/Encoding.UTF8.GetBytes("Hello, World!"); IHash digest = new SHA512Digest(); digest.Update(data, 0, data.Length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "")); } }
注意:在使用Bouncy Castle库之前,请确保已将其添加到项目中。你可以通过NuGet包管理器安装Bouncy Castle库。在.NET Core或.NET 5/6/7项目中,可以使用以下命令安装:
Install-Package BouncyCastle
在.NET Framework项目中,你需要手动将Bouncy Castle库添加到项目中,并引用相应的程序集。