跳至頁尾內容
開發者更新

BouncyCastle C#(開發者的工作原理)

BouncyCastle C# 是一個全面的程式庫,為 .NET 開發人員提供廣泛的加密算法和工具。 本指南旨在向初學者介紹 Bouncy Castle 的基本知識,強調其作為安全提供者的能力,並提供日常使用的實用範例。 我們還將學習如何與 IronPDF .NET PDF Library 一起使用它。

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 網站 下載最新版本的 Bouncy Castle package。 確保您選擇與您的項目需求匹配的正確版本。

整合到您的專案:下載後,將 Bouncy Castle 整合到您的 C# 專案中。 這通常涉及在專案設定中將程式庫新增為參考。

您也可以通過在 NuGet 包管理器的搜尋欄中搜尋 "Bouncycastle" 來下載和安裝它。

BouncyCastle C# (How It Works For Developer): Figure 1 - Download and install Bouncy Castle using NuGet Package Manager by searching Bouncycastle in the search bar of NuGet Package Manager

基本加密範例

在此範例中,我將展示如何在 C# 中使用 Bouncy Castle 的 AES (Advanced Encryption Standard) 進行簡單的加密情境。

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

這段程式碼片段展示瞭如何使用 Bouncy Castle 的加密程式庫在 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))
$vbLabelText   $csharpLabel

此範例相當基本,作為入門介紹。 在實際應用中,您應該考慮更穩健的做法,例如將鹽和 IV 與加密資料一起儲存,並處理在加密過程中可能引發的例外。

BouncyCastle C# (對開發者的工作方式):圖二 - 控制台輸出

進階使用和自訂

Bouncy Castle 並不限於基本功能。 它允許自訂並支持進階的加密算法。

NTRU Prime 和其他進階算法

Bouncy Castle 包含支援多種算法,包括進階的 NTRU Prime。 這賦予開發者選擇最適合其特定需求的算法的靈活性。

例外處理和安全最佳做法

在加密應用中,正確的例外處理至關重要。 Bouncy Castle 的方法可能會引發例外,正確處理這些例外可確保應用的強健性和安全性。

將 IronPDF 與 Bouncy Castle 結合

BouncyCastle C# (對開發者的工作方式):圖三 - IronPDF for .NET:C# PDF Library

IronPDF 通過提供工作處理 PDF 文件的功能來補充 Bouncy Castle,這些文件可以使用 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 包管理器在您的 Bouncy Castle C# 專案中整合 IronPDF,請按以下步驟進行:

  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 併入到您的專案中。從此處下載包含 DLL 的 ZIP 文件:IronPDF 直接下載。 解壓縮,然後將 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# (對開發者的工作方式):圖五 - IronPDF 授權資訊

總之,Bouncy Castle C# 和 IronPDF 的組合為在 .NET 應用中建立和保護 PDF 文件提供了解決方案。 Bouncy Castle 提供了必要的加密工具以保護資料,而 IronPDF 帶來了 PDF 的建立和操作的便捷性。 此整合在需要高級別文件安全性和機密性的情況下格外有價值。

對於那些有興趣探索 IronPDF 的人,該程式庫提供免費試用版本,允許開發人員進行試驗和評估其功能。 如果您決定將 IronPDF 整合到您的生產環境中,授權資訊和選項是可用的。

常見問題

如何在 .NET 應用中使用 BouncyCastle 來實施加密?

要在 .NET 應用中實施加密,您可以使用 BouncyCastle 程式庫,它提供了廣泛的加密算法。您可以從其官方網站或通過 NuGet 程式包管理工具下載它,然後在您的專案中新增為引用。

在 C# 中如何將 HTML 轉換為 PDF?

您可以在 C# 中使用 IronPDF 通過 RenderHtmlAsPdf 方法將 HTML 字串或 RenderHtmlFileAsPdf 方法將 HTML 文件轉換為 PDF 文件。

我可以在 .NET 應用中保護生成的 PDF 嗎?

是的,您可以在 .NET 應用中保護生成的 PDF。使用 IronPDF 建立 PDF 後,您可以使用 BouncyCastle 將其加密,方法是將 PDF 轉換為位元組陣列,應用加密算法如 AES,然後將加密資料保存到新文件中。

如何在 C# 專案中整合 BouncyCastle 與 PDF 程式庫?

要在 C# 專案中整合 BouncyCastle 與如 IronPDF 的 PDF 程式庫,您可以使用 NuGet 程式包管理工具安裝這兩個程式庫。使用 IronPDF 建立 PDF,並使用 BouncyCastle 為這些文件新增加密安全功能。

在 C# 中如何開始使用 BouncyCastle 的基本步驟是什麼?

首先通過 NuGet 程式包管理工具下載 BouncyCastle 程式庫,然後在您的 C# 專案中新增為引用。您可以開始使用其加密算法來實現多種用途,如加密、解密和數位簽名。

是否可以在購買之前測試 PDF 程式庫的功能?

是的,IronPDF 提供免費試用版本,開發者可以使用來探索和評估其功能,如 HTML 到 PDF 的轉換,然後再決定是否購買授權。

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

BouncyCastle 支持一系列高級加密算法,包括最尖端的 NTRU Prime,為選擇適合其應用的算法的開發者提供靈活性和安全性。

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

確保加密操作的安全性,您應該遵循最佳實踐,如安全儲存加密密鑰,正確處理異常,並在安全環境中進行操作,以防止未經授權的存取。

我可以在 .NET 應用中管理 PDF 文件嗎?

是的,您可以在 .NET 應用中使用 IronPDF 管理 PDF 文件。它允許您建立、編輯和將 HTML 轉換為 PDF,增強文件管理能力。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話