.NET 帮助 RandomNumberGenerator C# Curtis Chau 已更新:九月 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 的力量,来生成 PDF,每页上都会盖有一个唯一的、安全的文档 ID。 第 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 此方法使用 OS 的 RNG 的默认实现,生成一个适合密码学操作的密码。 这样会应用生成的安全密码,因此只有拥有密码访问权限的用户才能查看该文档。 此外,我们将保留一个包含我们设置权限的加密、安全的文档: 最佳实践和提示 始终使用 RandomNumberGenerator 处理任何与安全相关的内容。 避免在 ID、令牌或密码中使用 Random。 将敏感数据保留在日志或面向用户的消息之外,但要记录足够的内容以进行跟踪和审核。 考虑将时间戳和其他元数据与随机 ID 结合使用,以提高可追溯性。 使用 IronPDF 的内置安全功能与随机密钥结合使用,以保护您的文档。 验证随机数据的长度和编码,以确保在您的上下文中可用(例如,文件名、URL、条形码)。 摘要 结合 C# 的 RandomNumberGenerator 类与 IronPDF,您可以生成符合现代安全标准的安全、唯一的 PDF。 无论您是盖上唯一的 ID、生成加密密钥还是嵌入安全令牌,这种方法都可以帮助您: 防止文件伪造 改善可追溯性 保护 PDF 内的敏感数据 通过将这个类的密码学强度与 IronPDF 的多功能 PDF 工具结合,您的 PDF 解决方案将变得更安全和更专业。 自己试试吧! 准备好提升您的 PDF 安全性了吗? 尝试 IronPDF 免费试用 并开始今天使用安全随机数据进行实验! 常见问题解答 C# 中的随机数生成器类是什么? C# 中的随机数生成器类是 System.Security.Cryptography 命名空间的一部分,提供了生成加密安全随机数的方法。这在 PDF 加密和生成唯一标识符等场景中特别有用。 RandomNumberGenerator 如何用于 PDF 项目? 在 PDF 项目中,RandomNumberGenerator 可用于创建 PDF 加密的安全密码、生成唯一文件名,以及消除可预测的序列,从而增强文档的安全性和独特性。 为什么选择随机数生成器来生成随机数? 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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# 整数除法 (开发者用法) 如果您使用 / 运算符除以两个整数(int 类型),C# 会执行整数算术,通过舍弃小数部分来返回整数结果。 阅读更多 C# String Equals(开发者用法)