.NET幫助 RandomNumberGenerator C# Curtis Chau 更新日期:9月 4, 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 有時候,在處理 PDF 文件時,您可能需要生成隨機數或隨機字符串。 無論您是為 PDF 加密生成隨機數和密碼,創建唯一的文件名,避免可預測的序列,或是出於其他原因需要生成數字,使用 RandomNumberGenerator C# 類都可以幫助將您的 PDF 生成和編輯項目提升到新的水平。 不同於從 Random 類創建的基本隨機對象,這種加密隨機數生成器產生適合安全應用中加密操作的加密強隨機值。 在本文中,我們將探討: RandomNumberGenerator 是什麼以及它的重要性。 如何在 C# 中使用加密隨機數生成器來生成隨機數、隨機字符串和其他隨機數據以滿足加密需求。 將 RandomNumberGenerator 與 IronPDF 集成以使用生成的數字和字符串創建安全、唯一的 PDF 的實用示例。 增強您的 PDF 應用程序安全性和專業性的提示和最佳實踐。 RandomNumberGenerator 類是什麼 在深入了解 IronPDF 集成之前,讓我們簡要回顧一下 RandomNumberGenerator 的特殊之處。 它是 System.Security.Cryptography 命名空間的一部分。 它生成加密強隨機值作為隨機字節,比典型的 Random 類更安全。 對需要不可預測性的情景來說是理想選擇,例如生成安全令牌、密鑰、鹽和唯一標識符。 使用 AES-CTR DRBG、Fortuna 或操作系統提供的 CSPRNG 等加密算法。 使其對預測具有抵抗力。 適用於創建加密密鑰、密碼生成、安全令牌、唯一文件 ID 等任務。 這種強度源於依賴於操作系統底層安全隨機數生成器,使其對預測或逆向工程攻擊具有抵抗力。 不同於可能使用相同種子值產生相同序列的偽隨機數生成器,此類專為真正隨機和加密目標而設計。 為什麼使用 RandomNumberGenerator 而不是 C# 的 Random 類? 許多開發人員最初會使用 C# 的 Random 類來生成隨機整數,但其不適合高安全性場景。 其輸出中的模式可以被預測,尤其是在使用相同種子值或系統時間時,這意味著生成的數字可能會被猜測出來。 這發生是因為該方法使用簡單的模運算生成值,可能會在相同輸入下重複。 相反,RandomNumberGenerator 生成真正隨機的數字,來自 .NET Framework 或底層操作系統中的加密隨機數生成器。 這確保了沒有低值偏差,並且經常使用丟棄和重試策略來維持在一個下限(例如 int minValue)和排他性的上限(例如 int maxValue)之間的均勻分佈。 下圖說明了弱 RNG 與安全 RNG 之間的區別。 為什麼將 RandomNumberGenerator 與 IronPDF 一起使用 IronPDF 是一個強大的 .NET PDF 庫,使開發人員能夠創建、編輯和保護 PDF 文件。 涉及隨機性的常見使用場景包括: 唯一文件標識符:為 PDF 附加加密安全 ID,以進行跟蹤或驗證。 安全水印:嵌入隨機水印或代碼,以防止偽造。 加密密鑰或密碼:為 PDF 加密生成安全密鑰或密碼。 隨機內容:向 PDF 文檔中添加隨機唯一令牌或鹽以進行完整性驗證。 如何在 C# 中生成安全隨機數據 這是一個生成 128 位(16 字節)安全隨機令牌的簡單示例。 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); } 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); } Imports System Imports System.Security.Cryptography Public Shared Function GenerateSecureToken(Optional ByVal size As Integer = 16) As String Dim randomBytes(size - 1) As Byte RandomNumberGenerator.Fill(randomBytes) Return Convert.ToBase64String(randomBytes) End Function $vbLabelText $csharpLabel 此方法創建一個安全的字節數組並將其作為 Base64 字符串返回,非常適合在單元測試、文件名或保密 ID 中嵌入或跟蹤。 實用示例:向 PDF 文檔添加唯一文件 ID 讓我們結合 RandomNumberGenerator 和 IronPDF 的力量生成一個具有唯一、安全文件 ID 的 PDF 並將其打印在每一頁上。 步驟 1:生成安全文件 ID string GenerateDocumentId() { byte[] idBytes = new byte[12]; // 96-bit ID RandomNumberGenerator.Fill(idBytes); return BitConverter.ToString(idBytes).Replace("-", ""); } string GenerateDocumentId() { byte[] idBytes = new byte[12]; // 96-bit ID RandomNumberGenerator.Fill(idBytes); return BitConverter.ToString(idBytes).Replace("-", ""); } Private Function GenerateDocumentId() As String Dim idBytes(11) As Byte ' 96-bit ID RandomNumberGenerator.Fill(idBytes) Return BitConverter.ToString(idBytes).Replace("-", "") End Function $vbLabelText $csharpLabel 這會產生一個 24 字符的十六進制隨機字符串(例如 "4F3A2C9B7D1E8F0A5B6C7D8E")。 步驟 2:創建 PDF 並打印 ID 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 = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); }What this Code Does: 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 = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); }What this Code Does: Imports IronPdf Private Sub CreatePdfWithSecureId() Dim documentId = GenerateDocumentId() Dim renderer = New ChromePdfRenderer() ' Add a custom footer with the document ID renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With { .HtmlFragment = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", .DrawDividerLine = True } Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>") Dim outputPath As String = $"SecurePdf_{documentId}.pdf" pdf.SaveAs(outputPath) Console.WriteLine($"PDF saved as {outputPath}") End Sub 'INSTANT VB TODO TASK: The following line uses invalid syntax: 'What Me Code Does: $vbLabelText $csharpLabel 生成一個隨機數作為加密安全的唯一文件 ID。 將嵌入該 ID 的 HTML 渲染為 PDF。 在每頁添加底部註腳,顯示文件 ID 和時間戳。 使用 ID 在文件名中保存 PDF,以便於跟蹤。 完整運行代碼示例 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 = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); } } 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 = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", DrawDividerLine = true, }; var pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>"); string outputPath = $"SecurePdf_{documentId}.pdf"; pdf.SaveAs(outputPath); Console.WriteLine($"PDF saved as {outputPath}"); } } Imports IronPdf Imports IronPdf.Editing Imports System Imports System.Security.Cryptography Friend Class Program Public Shared Sub Main(ByVal args() As String) ' Create an instance of Program to run non-static methods 'INSTANT VB NOTE: The variable program was renamed since it may cause conflicts with calls to static members of the user-defined type with this name: Dim program_Conflict As New Program() program_Conflict.CreatePdfWithSecureId() End Sub Private Function GenerateDocumentId() As String Dim idBytes(11) As Byte ' 96-bit ID RandomNumberGenerator.Fill(idBytes) Return BitConverter.ToString(idBytes).Replace("-", "") End Function Private Sub CreatePdfWithSecureId() Dim documentId = GenerateDocumentId() Dim renderer = New ChromePdfRenderer() ' Add a custom footer with the document ID renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With { .HtmlFragment = $"<div style='text-align: center; font-size: 10px;'>Document ID: {documentId} - Generated on {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC</div>", .DrawDividerLine = True } Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Secure Document</h1><p>Document ID: {documentId}</p>") Dim outputPath As String = $"SecurePdf_{documentId}.pdf" pdf.SaveAs(outputPath) Console.WriteLine($"PDF saved as {outputPath}") End Sub End Class $vbLabelText $csharpLabel 輸出 高級用例:使用隨機密鑰進行安全 PDF 加密 IronPDF 支持 PDF 加密,為安全 PDF 創建提供強大支持。 您可以使用 RandomNumberGenerator 來創建強密碼或密鑰以用於加密: 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("<h1>Confidential PDF</h1><p>Access is restricted.</p>"); // 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}"); } } 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("<h1>Confidential PDF</h1><p>Access is restricted.</p>"); // 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}"); } } Imports IronPdf Imports IronPdf.Editing Imports System Imports System.Security.Cryptography Friend Class Program Public Shared Sub Main(ByVal args() As String) ' Create an instance of Program to run non-static methods 'INSTANT VB NOTE: The variable program was renamed since it may cause conflicts with calls to static members of the user-defined type with this name: Dim program_Conflict As New Program() program_Conflict.CreateEncryptedPdf() End Sub Private Function GenerateSecurePassword(Optional ByVal length As Integer = 12) As String Const chars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()" Dim data(length - 1) As Byte RandomNumberGenerator.Fill(data) Dim result(length - 1) As Char For i As Integer = 0 To length - 1 result(i) = chars.Chars(data(i) Mod chars.Length) Next i Return New String(result) End Function Private Sub CreateEncryptedPdf() Dim password As String = GenerateSecurePassword() Dim renderer = New ChromePdfRenderer() Dim pdf = renderer.RenderHtmlAsPdf("<h1>Confidential PDF</h1><p>Access is restricted.</p>") ' Set security settings pdf.SecuritySettings.UserPassword = password pdf.SecuritySettings.AllowUserAnnotations = False pdf.SecuritySettings.AllowUserCopyPasteContent = False pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint Dim filePath As String = "EncryptedSecurePdf.pdf" pdf.SaveAs(filePath) Console.WriteLine($"Encrypted PDF saved to {filePath} with password: {password}") End Sub End Class $vbLabelText $csharpLabel 此方法使用操作系統的 RNG 的默認實現,生成適合加密操作的密碼。 這將應用生成的安全密碼,所以只有擁有密碼的人才能查看文檔。 此外,我們將擁有一個加密的、安全的文檔及我們設置的權限: 最佳實踐和提示 始終對任何與安全相關的事務使用 RandomNumberGenerator。 避免將 Random 用於 ID、令牌或密碼。 避免在日志或用户界面中泄露敏感数据,但要记录足够的信息以便追踪和审计。 考慮使用時間戳和其他元數據來輔助隨機 ID,以提高可追溯性。 使用 IronPDF 的內建安全功能與隨機密鑰相結合來保護您的文檔。 驗證隨機數據的長度和編碼,以確保在您的應用場景中可用(例如,文件名、URL、條形碼)。 摘要 將 C# 的 RandomNumberGenerator 類與 IronPDF 集成,可以讓您生成符合當代安全標準的安全、唯一的 PDF。 無論是印制唯一 ID,生成加密密鑰,還是嵌入安全令牌,這種方法都有助於您: 防止文檔偽造 提高可追溯性 在 PDF 中保護敏感數據 通過將此類加密強度與 IronPDF 的多功能 PDF 工具結合,您的 PDF 解決方案將更加安全和專業。 自己試試吧! 準備提升您的 PDF 安全性了嗎? 試用 IronPDF 免費試用版,開始用安全隨機數據進行實驗吧! 常見問題解答 什麼是 C# 中的 RandomNumberGenerator 類? C# 中的 RandomNumberGenerator 類是 System.Security.Cryptography 命名空間的一部分,提供了生成加密安全隨機數的方法。它在 PDF 加密和生成唯一標識符等場景中特別有用。 如何在 PDF 項目中使用 RandomNumberGenerator? 在 PDF 項目中,RandomNumberGenerator 可用於創建 PDF 加密的安全密碼、生成唯一文件名,以及消除可預測的序列,提高文檔的安全性和唯一性。 為何選擇使用 RandomNumberGenerator 生成隨機數? RandomNumberGenerator 之所以被偏好用於生成隨機數,是因為它能生成加密安全的數字,適合需要安全性高的應用,如 PDF 文檔的加密。 RandomNumberGenerator 能夠幫助避免可預測的序列嗎? 是的,RandomNumberGenerator 通過生成加密安全的數字來幫助避免可預測的序列,確保序列的隨機性且不易預測。 RandomNumberGenerator 適合用於生成隨機字符串嗎? 是的,RandomNumberGenerator 可以藉由生成隨機字節來生成隨機字符串,這些字節可轉換為字符串。這對於創建安全密碼或 PDF 項目中的唯一標識符非常有用。 RandomNumberGenerator 在 C# 中的一些使用案例有哪些? RandomNumberGenerator 在 C# 中的使用案例包括 PDF 加密、生成唯一文件名、創建隨機密碼,以及任何需要加密安全隨機數的情況。 RandomNumberGenerator 如何提升 PDF 文檔的安全性? RandomNumberGenerator 通過提供加密安全的隨機數提升 PDF 文檔的安全性,這些數字可用於加密密鑰、密碼和其他安全措施來保護文檔內容。 使用 RandomNumberGenerator 相對於其他隨機數生成器的優勢是什麼? 使用 RandomNumberGenerator 的優勢在於其產生加密安全數字的能力,使其適合要求高安全級別的應用,如 PDF 文件加密。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#整數除法(開發者如何運作) 如果您使用/運算符除以兩個整數(int類型),C#會執行整數運算,捨棄小數部分並返回整數結果 閱讀更多 C#字符串等於(它如何對開...