跳過到頁腳內容
.NET幫助

RandomNumberGenerator C#

有時候,在處理 PDF 文件時,您可能會發現自己需要產生隨機數字或隨機字串。 無論您是要為 PDF 加密產生隨機數字和密碼、建立獨特的檔案名稱、避免可預測的序列,或是因其他原因需要產生數字,使用 RandomNumberGenerator C# 類別都能讓您的 PDF 產生和編輯專案更上一層樓。

與從 Random 類別建立的基本隨機物件不同,此加密隨機數發生器可產生適用於安全應用程式中加密操作的加密強隨機值。

在本文中,我們將探討

  • RandomNumberGenerator 是什麼,以及它為何重要。

  • 如何在 C# 中使用加密隨機數生成器來生成隨機數、隨機字串和其他用於加密的隨機資料。

  • 將 RandomNumberGenerator 與 IronPDF 整合的實用範例,以使用產生的數字和字串建立安全、獨特的 PDF。

  • 提升 PDF 應用程式安全性與專業性的技巧與最佳實務。

什麼是 RandomNumberGenerator 類別

在深入探討 IronPDF 整合之前,讓我們先簡單重溫一下 RandomNumberGenerator 的特別之處。

  • 它是 System.Security.Cryptography 命名空間的一部分。

  • 它以隨機 byte 的方式產生加密強的隨機值,比一般的隨機類更安全。

  • 它非常適用於需要不可預測性的場景,例如產生安全代號、金鑰、鹽和唯一識別碼。

  • 使用 AES-CTR DRBG、Fortuna 或 OS 提供的 CSPRNG 等密碼演算法。 使其能抵抗預測。

  • 最適合用於建立加密金鑰、密碼生成、安全代幣、唯一文件 ID 等任務。

此優勢來自於依賴作業系統底層的安全隨機數字產生器,使其能抵抗預測或逆向工程攻擊。 偽隨機數生成器可能會以相同的種子值產生相同的序列,與此不同,本類型是專為真正的隨機性和加密目的而設計。

為何使用 RandomNumberGenerator 而非 C# 的隨機類? 許多開發人員從 C# 的 Random 類開始,用來產生隨機整數,但它並非專為高安全性的情境所設計。 其輸出中的模式是可以預測的,尤其是當使用相同的種子值或系統時間時,意味著所產生的數字是可以猜測的。 出現這種情況的原因是,該方法使用簡單的模組算術運算產生數值,可以重複使用相同的輸入。 相比之下,RandomNumberGenerator 能產生真正的隨機數,這些隨機數源自 .NET Framework 或底層作業系統中的加密隨機數生成器。 這可確保沒有低值偏差,並經常使用捨棄與重試的策略,以維持下限 (例如 int minValue) 與排他上限 (例如 int maxValue) 之間的均勻分布。 下圖強調了弱 RNG 與安全 RNG 之間的差異。 !a href="/static-assets/pdf/blog/randomnumbergenerator-csharp/randomnumbergenerator-csharp-1.webp">"Weak" vs. Secure RNG ## 為何使用 IronPDF 的隨機數生成器 IronPDF for .NET 是一個強大的 .NET PDF 函式庫,可讓開發人員建立、編輯 PDF 文件並確保其安全性。 隨機性重要的常見用例包括 * **獨特的文件識別碼:**為 PDF 附加加密安全的 ID,以便追蹤或驗證。 * **安全水印:**嵌入隨機水印或代碼以防止偽造。 * **加密金鑰或密碼:**為 PDF 加密產生安全的金鑰或密碼。 * **隨機內容:**在 PDF 文件中加入隨機的唯一標記或鹽,以驗證完整性。 ## 如何在 C# 中產生安全的隨機資料 以下是一個產生 128 位元 (16 位元組) 安全隨機符記的簡單範例。 ```cs using System; using System.Security.Cryptography; public static string GenerateSecureToken(int size = 16) { byte[] randomBytes = new byte[size]; RandomNumberGenerator.Fill(randomBytes); return Convert.ToBase64String(randomBytes); } ``` 此方法會建立一個安全的位元組陣列,並將其回傳為 Base64 字串 - 非常適合嵌入或追蹤單元測試、檔名或安全 ID。 ## 實用範例:將唯一的文件 ID 新增至 PDF 文件。 讓我們結合 RandomNumberGenerator 和 IronPDF 的強大功能,產生 PDF,並在每頁上蓋上唯一、安全的文件 ID。 ### 步驟 1:產生安全文件 ID ```cs string GenerateDocumentId() { byte[] idBytes = new byte[12]; // 96-bit ID RandomNumberGenerator.Fill(idBytes); return BitConverter.ToString(idBytes).Replace("-", ""); } ``` 這會產生一個 24 個字元的十六進制隨機字串 (例如 "4F3A2C9B7D1E8F0A5B6C7D8E")。 ### 步驟 2:建立 PDF 並蓋上 ID 圖章 ```cs using IronPdf; void CreatePdfWithSecureId() { var documentId = GenerateDocumentId(); var renderer = new ChromePdfRenderer(); // Add a custom footer with the document ID renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter { HtmlFragment = $"
Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC
", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"

Secure Document

Document ID: {documentId}

"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); }What this Code Does: ``` * 為加密安全的唯一文件 ID 生成隨機數字。 * 渲染一個 HTML 到 PDF 的嵌入,ID. * 在每頁的頁尾加入文件 ID 和時間戳記。 * 使用檔案名稱中的 ID 儲存 PDF,以便於追蹤。 ### 完整工作程式碼範例 ```cs using IronPdf; using IronPdf.Editing; using System; using System.Security.Cryptography; class Program { public static void Main(string[] args) { // Create an instance of Program to run non-static methods var program = new Program(); program.CreatePdfWithSecureId() } string GenerateDocumentId() { byte[] idBytes = new byte[12]; // 96-bit ID RandomNumberGenerator.Fill(idBytes); return BitConverter.ToString(idBytes).Replace("-", ""); } void CreatePdfWithSecureId() { var documentId = GenerateDocumentId(); var renderer = new ChromePdfRenderer(); // Add a custom footer with the document ID renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter { HtmlFragment = $"
Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC
", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"

Secure Document

Document ID: {documentId}

"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); } } ``` #### 輸出 [帶有文檔 ID 的 PDF 文件](/static-assets/pdf/blog/randomnumbergenerator-csharp/randomnumbergenerator-csharp-2.webp) ## 進階使用案例:使用隨機金鑰的安全 PDF 加密 IronPDF 支援 [PDF 加密](https://ironpdf.com/examples/encryption-and-decryption),為安全的 PDF 建立提供強大的支援。 您可以使用 RandomNumberGenerator 來建立強大的密碼或加密金鑰: ```cs using IronPdf; using IronPdf.Editing; using System; using System.Security.Cryptography; class Program { public static void Main(string[] args) { // Create an instance of Program to run non-static methods var program = new Program(); program.CreateEncryptedPdf(); } string GenerateSecurePassword(int length = 12) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()"; byte[] data = new byte[length]; RandomNumberGenerator.Fill(data); char[] result = new char[length]; for (int i = 0; i < length; i++) { result[i] = chars[data[i] % chars.Length]; } return new string(result); } void CreateEncryptedPdf() { string password = GenerateSecurePassword(); var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf("

Confidential PDF

Access is restricted.

"); // Set security settings pdf.SecuritySettings.UserPassword = password; pdf.SecuritySettings.AllowUserAnnotations = false; pdf.SecuritySettings.AllowUserCopyPasteContent = false; pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint; string filePath = "EncryptedSecurePdf.pdf"; pdf.SaveAs(filePath); Console.WriteLine($"Encrypted PDF saved to {filePath} with password: {password}"); } } ``` 此方法使用作業系統 RNG 的預設實作,產生適合加密作業的密碼。 這將套用已產生的安全密碼,因此只有可存取密碼的使用者才能檢視文件。 [密碼保護彈出窗口](/static-assets/pdf/blog/randomnumbergenerator-csharp/randomnumbergenerator-csharp-3.webp) 此外,我們會留下一份加密的安全文件,並設定權限: !a href="/static-assets/pdf/blog/randomnumbergenerator-csharp/randomnumbergenerator-csharp-4.webp"> 加密 PDF 設定。 ## 最佳實務與技巧 * 任何與安全相關的事情,請務必使用 RandomNumberGenerator。 避免隨機使用 ID、token 或密碼。 * 將敏感資料置於日誌或面向使用者的訊息之外,但要記錄足夠的日誌以進行追蹤與稽核。 * 考慮在隨機 ID 旁邊使用時間戳記和其他元資料,以獲得更好的可追溯性。 * 使用 IronPDF 的內建安全功能結合隨機金鑰來保護您的文件。 * 驗證隨機資料長度和編碼,以確保在您的上下文中的可用性(例如,檔案名稱、URL、Barcode)。 ## 摘要 將 C# 的 RandomNumberGenerator 類與 IronPDF 整合,可讓您產生安全、獨特且符合現代安全標準的 PDF。 無論您是蓋印獨特的 ID、產生加密金鑰或嵌入安全代幣,這種方法都能幫到您: * 防止文件偽造 * 提高可追溯性 * 保護 PDF 中的敏感資料 通過將此類加密強度與 IronPDF 的多功能 PDF 工具相結合,您的 PDF 解決方案將變得更安全、更專業。 ### 親身體驗! 準備好提升您的 PDF 安全性了嗎? [立即試用 IronPDF 免費試用版](trial-license),開始體驗安全隨機資料!

常見問題解答

C# 中的 RandomNumberGenerator 類是什麼?

C# 中的 RandomNumberGenerator 類是 System.Security.Cryptography 命名空間的一部分,提供產生加密安全隨機數的方法。它在 PDF 加密和產生唯一識別碼等情境中特別有用。

如何在 PDF 專案中使用 RandomNumberGenerator?

在 PDF 專案中,RandomNumberGenerator 可用於建立 PDF 加密的安全密碼、產生獨特的檔案名稱,並消除可預測的序列,強化文件的安全性與唯一性。

為什麼選擇 RandomNumberGenerator 來產生隨機數?

RandomNumberGenerator 是產生隨機數的首選,因為它能產生加密安全的數字,使其適用於安全敏感的應用程式,例如 PDF 文件中的加密。

RandomNumberGenerator 能幫助避免可預測序列嗎?

是的,RandomNumberGenerator 透過產生加密安全的數字來幫助避免可預測序列,確保序列是隨機且不易預測的。

RandomNumberGenerator 適用於產生隨機字串嗎?

是的,RandomNumberGenerator 可以用來產生隨機字串,方法是先產生隨機位元組,然後再轉換成字串。這對於在 PDF 專案中建立安全密碼或獨特識別碼非常有用。

C# 中的 RandomNumberGenerator 有哪些用例?

C# 中 RandomNumberGenerator 的用例包括 PDF 加密、生成唯一文件名、創建隨機密碼以及任何需要加密安全隨機數的場景。

RandomNumberGenerator 如何增強 PDF 文件的安全性?

RandomNumberGenerator 透過提供加密安全的隨機數字來增強 PDF 文件的安全性,這些隨機數字可用於加密金鑰、密碼和其他保護文件內容的安全措施。

與其他隨機數生成器相比,使用 RandomNumberGenerator 有什麼優勢?

與其他隨機數字產生器相比,使用 RandomNumberGenerator 的優勢在於它能夠產生加密安全的數字,因此適用於需要高度安全性的應用程式,例如 PDF 檔案加密。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。