.NET 帮助

BouncyCastle C#(开发人员的工作原理)

发布 2024年一月14日
分享:

BouncyCastle C# Bouncy Castle 是一个综合库,为 .NET 开发人员提供了多种加密算法和工具。本指南旨在向初学者介绍 Bouncy Castle 的基础知识,强调其作为安全提供程序的功能,并提供日常使用的实际示例。我们还将学习如何将其与 IronPDF 图书馆

充气城堡简介

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

了解充气城堡的用途

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

开始使用 C&num 中的充气城堡;

用 C# 实现 Bouncy Castle 首先要设置环境并了解其基本组件。

设置

下载程序库:要开始使用,请从官方下载最新版本的充气城堡软件包。 网站.确保您选择了符合项目需求的正确版本。

集成到项目中:下载后,将 Bouncy Castle 集成到 C# 项目中。这通常需要在项目设置中将该库添加为引用。

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

BouncyCastle C#(开发人员如何使用):图 1 - 在 NuGet 软件包管理器的搜索栏中搜索"Bouncycastle",使用 NuGet 软件包管理器下载并安装 Bouncy Castle。

基本加密示例

在这个示例中,我将使用 AES 演示一个简单的加密方案 (高级加密标准) 用 C# 制作 Bouncy Castle。

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
VB   C#

本代码片段演示了如何创建一个基本的加密方法。处理任何可能抛出的异常以确保实现的安全性至关重要。要使用此方法,您需要调用 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))
VB   C#

这个示例非常基础,仅作为入门。在实际应用中,你应该考虑更稳健的做法,比如将盐和 IV 与加密数据一起存储,并处理加密过程中可能抛出的异常。

BouncyCastle C#(如何为开发人员工作):图 2 - 控制台输出

高级使用和定制

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

NTRU Prime 及其他高级算法

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

异常处理和安全最佳实践

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

将 IronPDF 与充气城堡相结合

BouncyCastle C#(如何为开发人员工作):图 3 - IronPDF for .NET:C# PDF 库

IronPDF 是对 Bouncy Castle 的补充,它提供了处理 PDF 文档的功能,然后可以使用 Bouncy Castle 的加密功能确保 PDF 文档的安全。下面介绍如何集成这两个功能强大的库:

IronPDF 的突出特点是它的 HTML 转 PDF 功能,并保留所有布局和样式。它能将网页内容转换为 PDF,适用于报告、发票和文档。你可以将 HTML 文件、URL 和 HTML 字符串无缝转换为 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");
    }
}
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
VB   C#

安装 IronPDF 库

适用于PDF的C# NuGet库

安装使用 NuGet

Install-Package IronPdf
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

适用于PDF的C# NuGet库

安装使用 NuGet

Install-Package IronPdf
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

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

第一步:
green arrow pointer

查看 IronPDFNuget 用于快速安装和部署。它有超过800万次下载,正在使用C#改变PDF。

适用于PDF的C# NuGet库 nuget.org/packages/IronPdf/
Install-Package IronPdf

考虑安装 IronPDF DLL 直接。下载并手动安装到您的项目或GAC表单中: IronPdf.zip

手动安装到你的项目中

下载DLL

使用 NuGet 软件包管理器安装

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

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

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

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

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

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

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

Install-Package IronPdf

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

使用 NuGet 网站安装

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

通过 DLL 安装

另外,您也可以使用 IronPDF 的 DLL 文件将其直接集成到您的项目中。从以下链接下载包含 DLL 的 ZIP 文件 链接.解压缩后,将 DLL 包含在您的项目中。

使用 IronPDF 生成 PDF

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

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
VB   C#

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

用弹跳城堡为 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
VB   C#

在该方法中,我们以字节形式读取 PDF 文件,使用之前定义的 SimpleEncryption 类对这些字节进行加密,然后将加密后的字节写入新文件。

结论

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

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

对于有兴趣探索 IronPDF,允许开发人员对其功能进行实验和评估。如果您决定将 IronPDF 集成到您的生产环境中,许可费从 $749 起。

< 前一页
C# 字符串插值(开发人员如何使用)
下一步 >
Math.NET C#(如何为开发者工作)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >