.NET 幫助

BouncyCastle C#(開發者如何使用)

Chipego
奇佩戈·卡林达
2024年1月14日
分享:

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 套件管理器透過在 NuGet 套件管理器的搜索欄中搜索「Bouncycastle」來下載和安裝它。

BouncyCastle C#(開發人員如何運作):圖1 - 使用NuGet套件管理器下載和安裝Bouncy Castle,通過在NuGet套件管理器的搜尋欄中搜尋「Bouncycastle」

基本加密範例

在此範例中,我將演示如何在 C# 中使用 Bouncy Castle 實現一個簡單的 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
{
    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 補充了 Bouncy Castle 的功能,提供了處理 PDF 文件的能力,然後可以利用 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 安裝

或者,您可以將IronPDF的DLL文件直接整合到您的專案中。 從這個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#(對開發者的運作方式)