跳過到頁腳內容
.NET幫助

RandomNumberGenerator C#

有時,在處理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之間的區別。

Weak vs. Secure 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的隨機數。

  • 將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。 避免將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 文件加密。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

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