温馨提示×

Bouncycastle在C#中的哈希算法

c#
小樊
92
2024-12-05 03:08:25
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Bouncy Castle是一个流行的加密库,提供了许多加密算法,包括哈希算法。在C#中,你可以使用Bouncy Castle库来实现各种哈希算法。以下是一些常见的哈希算法及其在Bouncy Castle中的实现:

  1. 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 = 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("-", ""));
    }
}
  1. 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 = 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("-", ""));
    }
}
  1. 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 = 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("-", ""));
    }
}
  1. 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 = 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库添加到项目中,并引用相应的程序集。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Bouncycastle在C#中的加密算法

0