.NET 幫助

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

發佈 2024年1月14日
分享:

BouncyCastle C#是一個全面的庫,為 .NET 開發人員提供多種加密算法和工具選擇。 本指南旨在向初學者介紹 Bouncy Castle 的基本知識,強調其作為安全提供者的功能,並提供日常使用的實用範例。 我們還將學習如何將其用於IronPDF圖書館。

Bouncy Castle 簡介

Bouncy Castle 是加密安全領域中強大且多功能的庫。 這是一個註冊的澳大利亞慈善項目,旨在為 Java 和 C# 提供高品質的安全服務。 該庫在基於MIT X Consortium License的許可下維護,該許可鼓勵廣泛使用和貢獻。

了解 Bouncy Castle 的用途

Bouncy Castle 作為安全提供者,提供廣泛的加密算法選擇。 它的多功能性使其能滿足各種安全需求,從基本的加密到複雜的數位簽章。 作為初學者,了解 Bouncy Castle 的範圍對於在專案中有效實施它至關重要。

入門 Bouncy Castle 在 C# 中

在 C# 中實作 Bouncy Castle 開始於設置環境並了解其基本組件。

設定

下載庫:要開始使用,請從其官方網站下載最新版本的Bouncy Castle套件。網站. 確保您選擇符合您項目需求的正確版本。

整合到您的專案中:下載後,將 Bouncy Castle 整合到您的 C# 專案中。 這通常涉及在專案設置中將庫添加為參考。

您也可以使用 NuGet 套件管理器下載和安裝,方法是在 NuGet 套件管理器的搜索欄中搜索「Bouncycastle」。

BouncyCastle C#(對開發人員的運作方式):圖1 - 在 NuGet 套件管理器中通過在搜索欄中搜索「Bouncycastle」下載並安裝 Bouncy Castle

基本加密範例

在此範例中,我將演示如何使用 AES 實現簡單的加密情境。(高级加密标准)使用 Bouncy Castle 在 C# 中。

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#

此範例相當基礎,作為簡介使用。 在實際應用中,您應該考慮更強健的做法,比如將鹽值和初始向量與加密數據一起存儲,並處理在加密過程中可能拋出的異常。

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。

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 函式庫

C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

立即開始在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer

查看 IronPDFNuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。

C# NuGet 程式庫用于 PDF 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網站上的IronPDF頁面:https://www.nuget.org/packages/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 並將其保存到檔案中。

使用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
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.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >