跳至页脚内容
.NET 帮助

BouncyCastle C#(开发者如何使用)

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

Bouncy Castle 简介

在加密安全领域,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 包管理器的搜索栏中搜索 "Bouncycastle" 来下载并安装它。

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

基本加密示例

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

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
{
    /// <summary>
    /// Encrypts data using AES encryption with a given password.
    /// </summary>
    /// <param name="message">The message to encrypt.</param>
    /// <param name="password">The password for key derivation.</param>
    /// <returns>The encrypted message as a byte array.</returns>
    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
{
    /// <summary>
    /// Encrypts data using AES encryption with a given password.
    /// </summary>
    /// <param name="message">The message to encrypt.</param>
    /// <param name="password">The password for key derivation.</param>
    /// <returns>The encrypted message as a byte array.</returns>
    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
	''' <summary>
	''' Encrypts data using AES encryption with a given password.
	''' </summary>
	''' <param name="message">The message to encrypt.</param>
	''' <param name="password">The password for key derivation.</param>
	''' <returns>The encrypted message as a byte array.</returns>
	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

此代码片段演示如何使用 C# 中 Bouncy Castle 的加密库创建基本加密方法。 要使用此方法,可以使用要加密的消息和密码调用 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 补充了 Bouncy Castle,提供了处理 PDF 文档的功能,可以使用 Bouncy Castle 的加密功能进行安全保护。 以下是如何集成这两个强大的库:

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

开始使用 IronPDF

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
{
    /// <summary>
    /// Creates a simple PDF from HTML content.
    /// </summary>
    /// <param name="filePath">The file path to save the PDF.</param>
    /// <param name="content">The HTML content to render as PDF.</param>
    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
{
    /// <summary>
    /// Creates a simple PDF from HTML content.
    /// </summary>
    /// <param name="filePath">The file path to save the PDF.</param>
    /// <param name="content">The HTML content to render as PDF.</param>
    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
	''' <summary>
	''' Creates a simple PDF from HTML content.
	''' </summary>
	''' <param name="filePath">The file path to save the PDF.</param>
	''' <param name="content">The HTML content to render as PDF.</param>
	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 文件:

using System.IO;
using System.Text;

// ... [Previous Bouncy Castle using statements]

public class PdfEncryption
{
    /// <summary>
    /// Encrypts a PDF file using AES encryption.
    /// </summary>
    /// <param name="inputFilePath">The path to the input PDF file.</param>
    /// <param name="outputFilePath">The path to save the encrypted PDF file.</param>
    /// <param name="password">The password used for encryption.</param>
    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);
    }
}
using System.IO;
using System.Text;

// ... [Previous Bouncy Castle using statements]

public class PdfEncryption
{
    /// <summary>
    /// Encrypts a PDF file using AES encryption.
    /// </summary>
    /// <param name="inputFilePath">The path to the input PDF file.</param>
    /// <param name="outputFilePath">The path to save the encrypted PDF file.</param>
    /// <param name="password">The password used for encryption.</param>
    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);
    }
}
Imports System.IO
Imports System.Text

' ... [Previous Bouncy Castle using statements]

Public Class PdfEncryption
	''' <summary>
	''' Encrypts a PDF file using AES encryption.
	''' </summary>
	''' <param name="inputFilePath">The path to the input PDF file.</param>
	''' <param name="outputFilePath">The path to save the encrypted PDF file.</param>
	''' <param name="password">The password used for encryption.</param>
	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,则可以获得 许可信息和选项

常见问题解答

如何在 .NET 应用程序中使用 BouncyCastle 实现加密?

要在 .NET 应用程序中实现加密,您可以使用 BouncyCastle 库,它提供了广泛的加密算法。您可以从其官方网站或通过 NuGet 包管理器下载,然后在项目中添加引用。

如何在 C# 中将 HTML 转换为 PDF?

您可以使用 IronPDF 在 C# 中将 HTML 转换为 PDF,利用 RenderHtmlAsPdf 方法用于 HTML 字符串,或使用 RenderHtmlFileAsPdf 方法用于 HTML 文件来生成 PDF 文档。

我可以保护在 .NET 应用程序中生成的 PDF 吗?

是的,您可以保护在 .NET 应用程序中生成的 PDF。在使用 IronPDF 创建 PDF 后,您可以使用 BouncyCastle 加密它,通过将 PDF 转换为字节数组,应用 AES 等加密算法,然后将加密数据保存到一个新文件。

如何在 C# 项目中将 BouncyCastle 与 PDF 库集成?

要将 BouncyCastle 与 IronPDF 等 PDF 库在 C# 项目中集成,您可以使用 NuGet 包管理器安装这两个库。使用 IronPDF 创建 PDF,并使用 BouncyCastle 为这些文档添加加密保护功能。

开始使用 BouncyCastle 在 C# 中的基本步骤是什么?

首先通过 NuGet 包管理器下载 BouncyCastle 库,然后将其添加为 C# 项目中的引用。您可以开始使用其加密算法,用于各种用途,如加密、解密和数字签名。

在购买之前,有方法测试 PDF 库功能吗?

是的,IronPDF 提供一个免费试用版本,开发者可以用来探索和评估其功能,比如 HTML 到 PDF 转换,从而在决定购买许可之前做出决策。

BouncyCastle 支持哪些高级加密算法?

BouncyCastle 支持一系列高级加密算法,包括像 NTRU Prime 这样的尖端算法,为开发者选择合适算法用于其应用程序提供了灵活性和安全性。

如何确保我的加密操作在 C# 中是安全的?

确保加密操作安全的关键是遵循最佳实践,如安全存储加密密钥,妥善处理异常,以及在安全环境中进行操作,以防止未经授权的访问。

我可以在 .NET 应用程序中管理 PDF 文档吗?

是的,您可以使用 IronPDF 在 .NET 应用程序中管理 PDF 文档。它允许您创建、编辑和将 HTML 转换为 PDF,增强文档管理功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。