.NET幫助 BouncyCastle C#(開發者的工作原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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 的範圍對於在您的項目中有效實施它至關重要。 在 C# 中開始使用 Bouncy Castle 在 C# 中實現 Bouncy Castle 始於設置環境並理解其基本組件。 設置 下載庫:要開始使用,請從其官方 Bouncy Castle 網站 下載最新版本的 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; } } 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,並處理在加密過程中可能引發的異常。 高級使用和自定義 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"); } } 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# 項目中,請按照以下步驟操作: 開啟 Visual Studio,並在解決方案管理器中右鍵單擊您的項目。 從彈出菜單中選擇“管理 NuGet 包…”。 轉到瀏覽標籤並搜索 IronPDF。 在搜索結果中選擇 IronPDF 庫並單擊安裝按鈕。 接受任何許可協議提示。 如果您想通過包管理器控制台將 IronPDF 包括在您的項目中,則在包管理器控制台運行以下命令: Install-Package IronPdf 這會將 IronPDF 下載並安裝到您的項目中。 通過 NuGet 網站安裝 要獲取 IronPDF 的詳細概述,包括其功能、兼容性和其他下載選項,請造訪 NuGet 網站上的 IronPDF 頁面 https://www.nuget.org/packages/IronPdf。 通過 DLL 安裝 或者,您可以直接將 IronPDF 集成到項目中,使用其 DLL 文件。從此處下載包含 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 類加密這些字節,然後將加密的字節寫入新文件。 結論 總之,Bouncy Castle C# 和 IronPDF 的組合為在 .NET 應用程序中創建和保護 PDF 文件提供了解決方案。 Bouncy Castle 提供了所需的加密工具來保護數據,而 IronPDF 則帶來了 PDF 創建和操作的便利。 在需要高度文檔安全性和保密性的場景中,這種集成尤其有價值。 對於有興趣探索 IronPDF 的人,該庫提供了一個免費試用版本,允許開發者實驗並評估其功能。 如果您決定將 IronPDF 集成到您的生產環境中,許可信息和選項可用。 常見問題解答 如何在 .NET 應用程式中使用 BouncyCastle 實現加密技術? 要在 .NET 應用程式中實現加密技術,可以使用 BouncyCastle 函式庫,它提供範圍廣泛的加密演算法。可以從其官方網站或通過 NuGet 套件管理器下載,然後在專案中將其添加為參考。 如何在 C# 中將 HTML 轉換為 PDF? 你可以使用 IronPDF 在 C# 中將 HTML 轉換為 PDF,利用 RenderHtmlAsPdf 方法處理 HTML 字串,或使用 RenderHtmlFileAsPdf 方法處理 HTML 文件,以生成 PDF 文檔。 可以在 .NET 應用程式中保護生成的 PDF 嗎? 是的,可以在 .NET 應用程式中保護生成的 PDF。在使用 IronPDF 創建 PDF 之後,可以利用 BouncyCastle 對其進行加密,方法是將 PDF 轉換為位元組數組,應用 AES 等加密演算法,並將加密數據保存到新文件中。 如何將 BouncyCastle 整合到 C# 專案中的 PDF 函式庫中? 要在 C# 專案中將 BouncyCastle 與 IronPDF 等 PDF 函式庫整合,可以使用 NuGet 套件管理器安裝這兩個函式庫。使用 IronPDF 來創建 PDF,並利用 BouncyCastle 向這些文檔添加加密安全功能。 開始使用 BouncyCastle C# 的基本步驟有哪些? 首先通過 NuGet 套件管理器下載 BouncyCastle 函式庫,然後將其作為參考添加到 C# 專案中。接下來可以使用其加密演算法,執行加密、解密和數字簽名等不同的加密操作。 購買之前有沒有可以測試 PDF 函式庫功能的方法? 是的,IronPDF 提供免費試用版,開發者可以使用它來探索和評估其功能,比如 HTML 到 PDF 轉換,以便在購買許可證之前做出決定。 BouncyCastle 支持哪些先進的加密演算法? BouncyCastle 支持範圍廣泛的高級加密演算法,其中包括最前沿的 NTRU Prime,為開發者選擇適合其應用程式的演算法提供靈活性和安全性。 如何確保我的加密操作在 C# 中是安全的? 通過遵循最佳實踐來確保加密操作的安全性,例如安全存儲加密密鑰、正確處理異常以及在安全環境中進行操作以防止未經授權的訪問。 可以在 .NET 應用程式中管理 PDF 文檔嗎? 是的,可以使用 IronPDF 在 .NET 應用程式中管理 PDF 文檔。它允許您創建、編輯和將 HTML 轉換為 PDF,提升文檔管理能力。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 字串插值(開發者的工作原理)Math.NET C#(開發者的工作原...