跳至頁尾內容
.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 之間的差異。

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 的預設實作,產生適合加密作業的密碼。

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

密碼保護彈出視窗

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

加密 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 項目中的唯一標識符非常有用。

RandomNumberGenerator 在 C# 中的一些使用案例有哪些?

RandomNumberGenerator 在 C# 中的使用案例包括 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)及全球政府機構。

雅各布於曼徹斯特大學(1998–2001)取得土木工程一等榮譽工程學士學位(BEng)。他在 1999 年於倫敦創立首家軟體公司,並於 2005 年開發出首批 .NET 元件,此後專注於解決微軟生態系統中的複雜問題。

其旗艦產品 IronPDF 與 Iron Suite .NET 函式庫在全球已累積超過 3,000 萬次 NuGet 安裝,其基礎程式碼持續驅動著全球廣泛使用的開發者工具。憑藉 25 年商業經驗與 41 年程式設計專業,雅各持續致力於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我