
BouncyCastle C#(开发者如何使用)| IronPDF
BouncyCastle C# 是一个全面的库,为 .NET 开发人员提供广泛的加密算法和工具选项。 本指南旨在向初学者介绍 Bouncy Castle 的基础知识,突显其作为安全提供者的能力,并提供日常使用的实际例子。 我们还将学习如何与 IronPDF 适用于 .NET PDF 库 一起使用它。
Bouncy Castle 简介
在加密安全领域,Bouncy Castle 脱颖而出,是一个功能强大且多用途的库。 它是一个注册的澳大利亚慈善项目,旨在为 Java 和 C# 提供高质量的安全服务。 该库根据 MIT X Consortium License 授权进行维护,鼓励广泛使用和贡献。
了解 Bouncy Castle 的目的
Bouncy Castle 作为安全提供者,提供了广泛的加密算法。 其多功能性使其能够满足从基本加密到复杂数字签名的各种安全需求。 作为初学者,了解 Bouncy Castle 的范围是有效地在项目中实施它的关键。
Getting Started with Bouncy Castle in C#
在 C# 中实现 Bouncy Castle 从设置环境和了解其基本组件开始。
设置
**下载库:**要开始使用,请从官方充气城堡网站下载最新版本的充气城堡软件包。 确保选择与您的项目需求匹配的正确版本。
**集成到您的项目中:**下载后,将 Bouncy Castle 集成到您的 C# 项目中。 这通常涉及在项目设置中添加库作为引用。
您也可以通过在 NuGet 包管理器的搜索栏中搜索 "Bouncycastle" 来下载并安装它。

基本加密示例
在本示例中,我将演示使用 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;
}
}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此代码片段演示如何使用 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));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))此示例相当基础,作为介绍。 在现实世界应用中,您应考虑更稳健的方法,例如将盐和 IV 与加密数据一起存储,以及处理加密过程中可能抛出的异常。

高级使用和自定义
Bouncy Castle 不仅限于基本功能。 它允许自定义,并支持高级加密算法。
NTRU Prime 和其他高级算法
Bouncy Castle 包括对多种算法(包括高级 NTRU Prime)的支持。 这使得开发人员能够根据特定需求选择最合适的算法。
异常处理和安全最佳实践
在加密应用中,适当的异常处理至关重要。 Bouncy Castle 的方法可以抛出异常,正确处理这些异常可以确保应用程序的稳健性和安全性。
将 IronPDF 与 Bouncy Castle 集成

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");
}
}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使用 NuGet 包管理器安装
要通过 NuGet 包管理器将 IronPDF 集成到您的 Bouncy Castle C# 项目中,请按照以下步骤操作:
- 打开 Visual Studio,并在解决方案资源管理器中右键单击项目。
- 从上下文菜单中选择 "管理 NuGet 包..."。
- 转到浏览选项卡,搜索 IronPDF。
- 从搜索结果中选择 IronPDF 库,然后单击安装按钮。
- 接受任何许可协议提示。
如果您想通过包管理器控制台在项目中包含 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);
}
}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在此代码中,我们使用 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);
}
}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在此方法中,我们将 PDF 文件读取为字节,使用我们之前定义的 SimpleEncryption 类加密这些字节,然后将加密的字节写入一个新文件。
结论
总结来说,Bouncy Castle C# 和 IronPDF 的组合为在 .NET 应用程序中创建和保护 PDF 文档提供了解决方案。 Bouncy Castle 提供必要的加密工具来保护数据,而 IronPDF 带来了轻松的 PDF 创建和操作。 这种集成在需要高水平的文档安全和保密的情况下尤其有价值。
对于那些有兴趣深入了解 IronPDF 的开发者,该库提供了免费试用版,允许开发人员实验和评估其功能。 如果您决定在生产环境中集成 IronPDF,则可以获得 许可信息和选项。

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


