跳過到頁腳內容
.NET HELP

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 位元組) 安全隨機符記的簡單範例。

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。

實用範例:將唯一的文件 ID 新增至 PDF 文件。

讓我們結合 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 生成隨機數字。

  • 渲染一個 HTML 到 PDF 的嵌入,ID.

  • 在每頁的頁尾加入文件 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

輸出

帶有文檔 ID 的 PDF 文件

進階使用案例:使用隨機金鑰的安全 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 的預設實作,產生適合加密作業的密碼。

這將套用已產生的安全密碼,因此只有可存取密碼的使用者才能檢視文件。

密碼保護彈出窗口

此外,我們會留下一份加密的安全文件,並設定權限:

!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 免費試用版,開始體驗安全隨機資料!

常見問題解答

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 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。