.NET 도움말 RandomNumberGenerator C# 커티스 차우 업데이트됨:12월 20, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 Sometimes, when working with PDF documents, you might find yourself needing to generate random numbers or random strings. Whether you're generating random numbers and passwords for PDF encryption, creating unique file names, avoiding predictable sequences, or need to generate numbers for any other reason, using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level. Unlike a basic random object created from the Random class, this cryptographic random number generator produces cryptographically strong random values suitable for cryptographic operations in secure applications. In this article, we'll explore: What RandomNumberGenerator is and why it matters. How to use a cryptographic random number generator in C# to generate random numbers, random strings, and other random data for cryptographic purposes. Practical examples of integrating RandomNumberGenerator with IronPDF to create secure, unique PDFs using the generated numbers and strings. Tips and best practices to boost security and professionalism in your PDF applications. What is the RandomNumberGenerator Class Before diving into IronPDF integration, let's briefly revisit what makes RandomNumberGenerator special. It is part of the System.Security.Cryptography namespace. It generates cryptographically strong random values as random byte, much more secure than the typical Random class. It's ideal for scenarios requiring unpredictability, such as generating secure tokens, keys, salts, and unique identifiers. Uses Cryptographic algorithms like AES-CTR DRBG, Fortuna, or OS-provided CSPRNGs. Making it resistant to prediction. Best used for tasks such as creating cryptographic keys, password generation, secure tokens, unique document IDs. This strength comes from relying on the operating system’s underlying secure random number generators, making it resistant to prediction or reverse-engineering attacks. Unlike pseudo random number generators that may produce the same sequence with the same seed value, this class is designed for true randomness and cryptographic purposes. Why Use RandomNumberGenerator Instead of C#'s Random Class? Many developers start with C#’s Random class for generating random integers, but it’s not designed for high-security scenarios. Patterns in its output can be predicted, especially if the same seed value or system time is used, meaning the numbers generated could be guessed. This happens because the method generates values using simple modular arithmetic operations that can repeat with the same input. In contrast, RandomNumberGenerator produces truly random numbers, derived from cryptographic random number generators in the .NET Framework or underlying OS. This ensures no low value bias and often uses a discard and retry strategy to maintain uniform distribution between a lower bound (e.g., int minValue) and an exclusive upper bound (e.g., int maxValue). The illustration below highlights the difference between a weak RNG and a secure one. Why Use RandomNumberGenerator with IronPDF IronPDF is a robust .NET PDF library, enabling developers to create, edit, and secure PDF documents. Common use cases where randomness matters includes: Unique Document Identifiers: Attach cryptographically secure IDs to PDFs for tracking or validation. Secure Watermarks: Embed random watermarks or codes that deter forgery. Encryption Keys or Passwords: Generate secure keys or passwords for PDF encryption. Random Content: Add random unique tokens or salts to PDF documents for integrity verification. How to Generate Secure Random Data in C Here's a simple example of generating a 128-bit (16-byte) secure random token. 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); } $vbLabelText $csharpLabel This method creates a secure byte array and returns it as a Base64 string — perfect for embedding or tracking in unit tests, filenames, or secure IDs. Practical Example: Adding Unique Document IDs to PDF Documents Let's combine the power of RandomNumberGenerator and IronPDF to generate a PDF with a unique, secure document ID stamped on each page. Step 1: Generate a Secure Document 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("-", ""); } $vbLabelText $csharpLabel This produces a 24-character hex random string (e.g. "4F3A2C9B7D1E8F0A5B6C7D8E"). Step 2: Create the PDF and Stamp the 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: $vbLabelText $csharpLabel Generates a random number for a cryptographically secure, unique document ID. Renders an HTML to PDF embedding that ID. Adds a footer on every page with the document ID and timestamp. Saves the PDF using the ID in the filename for easy tracking. Full Working Code Example 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}"); } } $vbLabelText $csharpLabel Output Advanced Use Case: Secure PDF Encryption with Random Keys IronPDF supports PDF encryption, providing strong support for secure PDF creation. You can use RandomNumberGenerator to create strong passwords or keys for encryption: 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}"); } } $vbLabelText $csharpLabel This method uses default implementation from the OS’s RNG, producing a password suitable for cryptographic operations. This will apply the generated secure password, so only users with access to the passwords will be able to view the document. Additionally, we will be left with a encrypted, secure document with our set permissions: Best Practices and Tips Always use RandomNumberGenerator for anything security-related. Avoid Random for IDs, tokens, or passwords. Keep sensitive data out of logs or user-facing messages, but log enough to track and audit. Consider using timestamps and other metadata alongside random IDs for better traceability. Use IronPDF's built-in security features combined with random keys to protect your documents. Validate random data length and encoding to ensure usability in your context (e.g., filenames, URLs, barcodes). Summary Integrating C#'s RandomNumberGenerator class with IronPDF empowers you to generate secure, unique PDFs that meet modern security standards. Whether you're stamping unique ID's, generating encryption keys, or embedding secure tokens, this approach helps you: Prevent document forgery Improve traceability Secure sensitive data within your PDFs By combining the cryptographic strength of this class with IronPDF's versatile PDF tools, your PDF solutions become safer and more professional. Try It Yourself! Ready to boost your PDF security? Try the IronPDF free trial and start experimenting with secure random data today! 자주 묻는 질문 C#에서 RandomNumberGenerator 클래스란 무엇인가요? C#의 RandomNumberGenerator 클래스는 암호학적으로 안전한 난수를 생성하는 메서드를 제공하는 System.Security.Cryptography 네임스페이스의 일부입니다. 이 클래스는 PDF 암호화 및 고유 식별자 생성과 같은 시나리오에서 특히 유용합니다. PDF 프로젝트에서 난수 생성기는 어떻게 사용할 수 있나요? PDF 프로젝트에서 난수 생성기를 사용하면 PDF 암호화를 위한 보안 암호를 생성하고, 고유한 파일 이름을 생성하고, 예측 가능한 순서를 제거하여 문서의 보안과 고유성을 강화할 수 있습니다. 난수 생성에 RandomNumberGenerator를 선택하는 이유는 무엇인가요? 난수 생성에 선호되는 RandomNumberGenerator는 암호학적으로 안전한 숫자를 생성하므로 PDF 문서의 암호화와 같이 보안에 민감한 애플리케이션에 적합합니다. 예측 가능한 시퀀스를 피하는 데 RandomNumberGenerator가 도움이 될 수 있나요? 예, RandomNumberGenerator는 암호학적으로 안전한 숫자를 생성하여 예측 가능한 시퀀스를 피하고, 시퀀스가 무작위이며 쉽게 예측할 수 없도록 합니다. RandomNumberGenerator는 난수 문자열 생성에 적합한가요? 예, RandomNumberGenerator를 사용하면 먼저 임의의 바이트를 생성하여 임의의 문자열을 생성한 다음 이를 문자열로 변환할 수 있습니다. 이 기능은 PDF 프로젝트에서 보안 비밀번호나 고유 식별자를 만드는 데 유용합니다. C#에서 난수 생성기의 사용 사례에는 어떤 것이 있나요? C#에서 RandomNumberGenerator의 사용 사례에는 PDF 암호화, 고유 파일 이름 생성, 임의의 비밀번호 생성 및 암호화 방식으로 안전한 난수가 필요한 모든 시나리오가 포함됩니다. 난수 생성기는 PDF 문서의 보안을 어떻게 강화하나요? RandomNumberGenerator는 암호화 키, 비밀번호 및 문서 콘텐츠를 보호하기 위한 기타 보안 조치에 사용할 수 있는 암호학적으로 안전한 난수를 제공하여 PDF 문서의 보안을 강화합니다. 다른 난수 생성기보다 RandomNumberGenerator를 사용하면 어떤 이점이 있나요? 다른 난수 생성기에 비해 RandomNumberGenerator를 사용할 때의 장점은 암호학적으로 안전한 숫자를 생성할 수 있어 PDF 파일 암호화와 같이 높은 수준의 보안이 필요한 애플리케이션에 적합하다는 점입니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 업데이트됨 8월 5, 2025 C# Switch Pattern Matching (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDFC# String Equals (How it Works for ...
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기
업데이트됨 8월 5, 2025 C# Switch Pattern Matching (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기