.NET 帮助

BouncyCastle C#(开发人员如何使用)

Chipego
奇佩戈-卡琳达
2024年一月14日
分享:

BouncyCastle C# 是一个全面的库,为 .NET 开发人员提供了广泛的加密算法和工具选项。 本指南旨在向初学者介绍 Bouncy Castle 的基础知识,强调其作为安全提供商的功能,并提供日常使用的实际示例。 我们还将了解如何将其与IronPDF .NET PDF Library一起使用。

充气城堡简介

Bouncy Castle 是加密安全领域功能强大、用途广泛的库。 这是一个在澳大利亚注册的慈善项目,旨在为 Java 和 C# 提供高质量的安全服务。 该库根据 MIT X Consortium License 许可证进行维护,该许可证鼓励广泛使用和贡献。

了解 Bouncy Castle 的用途

Bouncy Castle 是一家安全供应商,提供各种加密算法。 它的多功能性使其能够满足从基本加密到复杂数字签名的各种安全需求。 作为初学者,了解 Bouncy Castle 的范围是在项目中有效实施它的关键。

在C#中入门Bouncy Castle

用 C# 实现 Bouncy Castle 从设置环境和了解其基本组件开始。

设置

下载库:首先,请从官方Bouncy Castle 网站下载 Bouncy Castle 软件包的最新版本。 确保您选择的版本符合您的项目需求。

集成到您的项目中:下载后,将 Bouncy Castle 集成到您的 C# 项目中。 这通常涉及在项目设置中添加库作为参考。

您也可以使用 NuGet 软件包管理器下载并安装,方法是在 NuGet 软件包管理器的搜索栏中搜索 "Bouncycastle"。

BouncyCastle C#(如何为开发者工作):图1 - 使用NuGet包管理器进行下载并安装Bouncy Castle,通过在NuGet包管理器的搜索栏中搜索“Bouncycastle”

基本加密示例

在这个例子中,我将演示一个简单的加密场景,使用AES(高级加密标准)和Bouncy Castle在C#中。

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Text;
public class SimpleEncryption
{
    public static byte[] EncryptData(string message, string password)
    {
        // Generate a random salt
        var salt = new byte[8];
        new SecureRandom().NextBytes(salt);
        // Derive key and IV from the password and salt
        Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();
        generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000);
        ParametersWithIV keyParam = (ParametersWithIV)generator.GenerateDerivedMacParameters(256 + 128);
        // Create AES cipher in CBC mode with PKCS7 padding
        var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));
        cipher.Init(true, keyParam);
        // Convert message to byte array and encrypt
        byte[] inputBytes = Encoding.UTF8.GetBytes(message);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0);
        cipher.DoFinal(outputBytes, length);
        return outputBytes;
    }
}
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Text;
public class SimpleEncryption
{
    public static byte[] EncryptData(string message, string password)
    {
        // Generate a random salt
        var salt = new byte[8];
        new SecureRandom().NextBytes(salt);
        // Derive key and IV from the password and salt
        Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();
        generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000);
        ParametersWithIV keyParam = (ParametersWithIV)generator.GenerateDerivedMacParameters(256 + 128);
        // Create AES cipher in CBC mode with PKCS7 padding
        var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));
        cipher.Init(true, keyParam);
        // Convert message to byte array and encrypt
        byte[] inputBytes = Encoding.UTF8.GetBytes(message);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0);
        cipher.DoFinal(outputBytes, length);
        return outputBytes;
    }
}
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Crypto.Engines
Imports Org.BouncyCastle.Crypto.Generators
Imports Org.BouncyCastle.Crypto.Modes
Imports Org.BouncyCastle.Crypto.Parameters
Imports Org.BouncyCastle.Security
Imports System.Text
Public Class SimpleEncryption
	Public Shared Function EncryptData(ByVal message As String, ByVal password As String) As Byte()
		' Generate a random salt
		Dim salt = New Byte(7){}
		Call (New SecureRandom()).NextBytes(salt)
		' Derive key and IV from the password and salt
		Dim generator As New Pkcs5S2ParametersGenerator()
		generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, 1000)
		Dim keyParam As ParametersWithIV = CType(generator.GenerateDerivedMacParameters(256 + 128), ParametersWithIV)
		' Create AES cipher in CBC mode with PKCS7 padding
		Dim cipher = New PaddedBufferedBlockCipher(New CbcBlockCipher(New AesEngine()))
		cipher.Init(True, keyParam)
		' Convert message to byte array and encrypt
		Dim inputBytes() As Byte = Encoding.UTF8.GetBytes(message)
		Dim outputBytes(cipher.GetOutputSize(inputBytes.Length) - 1) As Byte
		Dim length As Integer = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0)
		cipher.DoFinal(outputBytes, length)
		Return outputBytes
	End Function
End Class
$vbLabelText   $csharpLabel

本代码片段演示了如何创建基本加密方法。 必须处理任何可能抛出的异常,以确保实现的安全性。 要使用此方法,您需要调用EncryptData,并提供您要加密的信息和密码。 例如

string message = "Hello, this is a test message!";
string password = "StrongPassword123";
byte[] encryptedMessage = SimpleEncryption.EncryptData(message, password);
Console.WriteLine("Original Message: " + message);
Console.WriteLine("Encrypted Message: " + BitConverter.ToString(encryptedMessage));
string message = "Hello, this is a test message!";
string password = "StrongPassword123";
byte[] encryptedMessage = SimpleEncryption.EncryptData(message, password);
Console.WriteLine("Original Message: " + message);
Console.WriteLine("Encrypted Message: " + BitConverter.ToString(encryptedMessage));
Dim message As String = "Hello, this is a test message!"
Dim password As String = "StrongPassword123"
Dim encryptedMessage() As Byte = SimpleEncryption.EncryptData(message, password)
Console.WriteLine("Original Message: " & message)
Console.WriteLine("Encrypted Message: " & BitConverter.ToString(encryptedMessage))
$vbLabelText   $csharpLabel

本示例非常简单,仅作为介绍。 在实际应用中,您应该考虑更稳健的做法,比如将盐和 IV 与加密数据一起存储,并处理加密过程中可能抛出的异常。

BouncyCastle C#(对于开发人员的工作原理):图2 - 控制台输出

高级使用和定制

Bouncy Castle 不限于基本功能。 它允许自定义并支持高级加密算法。

NTRU Prime 和其他高级算法

Bouncy Castle 包括对多种算法的支持,其中包括先进的NTRU Prime。 这样,开发人员就可以根据自己的具体需求灵活选择最合适的算法。

异常处理和安全最佳实践

正确的异常处理在加密应用程序中至关重要。 Bouncy Castle 的方法会抛出异常,正确处理这些异常可确保应用程序的稳健性和安全性。

将 IronPdf 与 Bouncy Castle 结合使用

BouncyCastle C#(对开发者的工作原理):图3 - IronPDF for .NET:C# PDF库

IronPDF 通过提供处理 PDF 文档的功能来补充 Bouncy Castle,这些文档随后可以使用 Bouncy Castle 的加密功能进行安全保护。 以下是如何整合这两个功能强大的库:

IronPDF 的突出特点是其HTML 转换为 PDF 的功能,能够保留所有布局和样式。 它可将网页内容转换为 PDF 文件,适用于报告、发票和文档。 您可以将 HTML 文件、URL 和 HTML 字符串无缝转换为 PDF。

开始使用IronPDF

立即在您的项目中开始使用IronPDF,并享受免费试用。

第一步:
green arrow pointer


using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

使用 NuGet 包管理器安装

要使用 NuGet 包管理器将 IronPDF 集成到您的 Bouncy Castle C# 项目中,请按照以下步骤操作:

  1. 打开 Visual Studio,在解决方案资源管理器中右键单击您的项目。

  2. 从上下文菜单中选择 "管理 NuGet 软件包..."。

  3. 转到浏览选项卡并搜索 IronPDF。

  4. 从搜索结果中选择 IronPdf 库,然后点击安装按钮。

  5. 接受任何许可协议提示。

    如果您想通过软件包管理器控制台在项目中包含 IronPdf,那么请在软件包管理器控制台中执行以下命令:

Install-Package IronPdf

它会获取 IronPDF 并将其安装到你的项目中。

使用 NuGet 网站安装

有关 IronPDF 的详细概述,包括其功能、兼容性和其他下载选项,请访问 NuGet 网站上的 IronPDF 页面 https://www.nuget.org/packages/IronPdf

通过 DLL 安装

或者,您可以使用其 DLL 文件将 IronPDF 直接集成到您的项目中。 从这个IronPDF直接下载下载包含 DLL 的 ZIP 文件。 解压缩,并将 DLL 包含到您的项目中。

使用 IronPDF 生成 PDF

首先,让我们使用IronPDF创建一个简单的PDF文档

using IronPdf;
public class PdfGenerator
{
    public static void CreateSimplePdf(string filePath, string content)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs(filePath);
    }
}
using IronPdf;
public class PdfGenerator
{
    public static void CreateSimplePdf(string filePath, string content)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs(filePath);
    }
}
Imports IronPdf
Public Class PdfGenerator
	Public Shared Sub CreateSimplePdf(ByVal filePath As String, ByVal content As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		pdf.SaveAs(filePath)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此代码中,我们使用IronPDF的ChromePdfRenderer类将HTML内容渲染为PDF并将其保存到文件中。

使用 Bouncy Castle 为 PDF 加密

生成 PDF 后,我们可以使用 Bouncy Castle 对其进行加密。 在这里,我们将修改EncryptData方法以处理PDF文件:

// ... [Previous Bouncy Castle using statements]
public class PdfEncryption
{
    public static void EncryptPdfFile(string inputFilePath, string outputFilePath, string password)
    {
        // Read the PDF file
        byte[] pdfBytes = File.ReadAllBytes(inputFilePath);
        // Encrypt the PDF bytes
        byte[] encryptedBytes = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password);
        // Write the encrypted bytes to a new file
        File.WriteAllBytes(outputFilePath, encryptedBytes);
    }
}
// ... [Previous Bouncy Castle using statements]
public class PdfEncryption
{
    public static void EncryptPdfFile(string inputFilePath, string outputFilePath, string password)
    {
        // Read the PDF file
        byte[] pdfBytes = File.ReadAllBytes(inputFilePath);
        // Encrypt the PDF bytes
        byte[] encryptedBytes = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password);
        // Write the encrypted bytes to a new file
        File.WriteAllBytes(outputFilePath, encryptedBytes);
    }
}
' ... [Previous Bouncy Castle using statements]
Public Class PdfEncryption
	Public Shared Sub EncryptPdfFile(ByVal inputFilePath As String, ByVal outputFilePath As String, ByVal password As String)
		' Read the PDF file
		Dim pdfBytes() As Byte = File.ReadAllBytes(inputFilePath)
		' Encrypt the PDF bytes
		Dim encryptedBytes() As Byte = SimpleEncryption.EncryptData(Encoding.UTF8.GetString(pdfBytes), password)
		' Write the encrypted bytes to a new file
		File.WriteAllBytes(outputFilePath, encryptedBytes)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此方法中,我们将 PDF 文件读取为字节,使用我们先前定义的SimpleEncryption类加密这些字节,然后将加密的字节写入一个新文件。

结论

BouncyCastle C#(开发人员如何使用):图5 - IronPDF 许可证信息

总之,Bouncy Castle C# 和 IronPDF 的结合为在 .NET 应用程序中创建和保护 PDF 文档提供了解决方案。 Bouncy Castle 提供了保护数据安全所需的加密工具,而 IronPDF 则带来了 PDF 创建和操作的便捷性。 这种整合在需要高度文件安全和保密的情况下尤为重要。

对于那些有兴趣探索 IronPdf 的人,该库提供了免费试用版,允许开发人员进行实验并评估其功能。 如果您决定将IronPDF集成到生产环境中,许可证信息和选项可以查看。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# 字符串插值(开发者如何使用)
下一步 >
Math.NET C#(它如何为开发人员工作)