跳過到頁腳內容
.NET幫助

C# AES加密(對開發者如何理解的工作)

AES(Advanced Encryption Standard) 是最常用的對稱加密算法之一。 它使用相同的金鑰來加密和解密資料,使得 AES 加密在許多應用程式中都能高效快速地保護敏感資料的安全。

本教學將著重於 C# 中的 AES 加密,使用 AES 類別加密和解密資料,以及 IronPDF Library。 我們將涵蓋實例、闡述加密過程,並了解如何使用 Cipher Block Chaining (CBC) 模式來提高安全性。 我們還會討論加密金鑰管理和初始化向量 (IV) 的作用。

C# 中 AES 加密的介紹

進階加密標準 (Advanced Encryption Standard, AES) 是美國國家標準與技術研究院 (National Institute of Standards and Technology, NIST) 標準化的對稱加密演算法。 該演算法的金鑰大小可為 128、192 或 256 位元,對於加密機密資料而言具有高度安全性。 它使用相同的加密金鑰來加密和解密資料。

AES 的工作原理是將原始資料分割成區塊,並對這些區塊進行轉換。 它以不同的密碼模式運作,例如 CBC(密碼區塊連結)和 Electronic CodeBook (ECB),每種模式都提供不同的安全功能。

AES 在 C# 中的運作方式

C# 中的 AES 加密算法是 System.Security.Cryptography 命名空間的一部分。 此命名空間包含 AES 類別,可讓我們建立 AES 的實例、指定金鑰大小、密碼模式和填充模式,然後再使用秘密金鑰加密和解密資料。

若要在 C# 中使用 AES,請遵循以下基本步驟:

  1. 使用 Aes.Create() 建立 AES 類別的實例。 2.設定金鑰、IV 及其他相關參數,例如密碼模式。 3.使用 ICryptoTransform 介面加密資料,並將其寫入 MemoryStream。 4.使用相同的金鑰和 IV 解密資料。

讓我們用 C# 建立一個基本的加密程序和解密程序。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    // Declare a static byte array for encrypted data
    public static byte[] encryptedData;

    // Main method to demonstrate encryption and decryption
    public static void Main(string[] args)
    {
        // String plaintext to be encrypted
        string plaintext = "This is some sensitive data!";
        string key = "abcdefghijklmnop"; // 128-bit key (16 characters)

        // Encrypt the plaintext
        string ciphertext = Encrypt(plaintext, key);
        Console.WriteLine("Encrypted Data: " + ciphertext);

        // Decrypt the ciphertext
        string decryptedData = Decrypt(ciphertext, key);
        Console.WriteLine("Decrypted Data: " + decryptedData);
    }

    // Method to encrypt data
    public static string Encrypt(string plaintext, string key)
    {
        // Create a new instance of the AES encryption algorithm
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create an encryptor to perform the stream transform
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            // Create the streams used for encryption
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a CryptoStream using the encryptor
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(plaintext);
                    }
                }
                // Store the encrypted data in the public static byte array
                encryptedData = ms.ToArray();
                return Convert.ToBase64String(encryptedData);
            }
        }
    }

    // Method to decrypt data
    public static string Decrypt(string ciphertext, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create a decryptor to perform the stream transform
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            // Create the streams used for decryption
            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }
    }
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    // Declare a static byte array for encrypted data
    public static byte[] encryptedData;

    // Main method to demonstrate encryption and decryption
    public static void Main(string[] args)
    {
        // String plaintext to be encrypted
        string plaintext = "This is some sensitive data!";
        string key = "abcdefghijklmnop"; // 128-bit key (16 characters)

        // Encrypt the plaintext
        string ciphertext = Encrypt(plaintext, key);
        Console.WriteLine("Encrypted Data: " + ciphertext);

        // Decrypt the ciphertext
        string decryptedData = Decrypt(ciphertext, key);
        Console.WriteLine("Decrypted Data: " + decryptedData);
    }

    // Method to encrypt data
    public static string Encrypt(string plaintext, string key)
    {
        // Create a new instance of the AES encryption algorithm
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create an encryptor to perform the stream transform
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            // Create the streams used for encryption
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a CryptoStream using the encryptor
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(plaintext);
                    }
                }
                // Store the encrypted data in the public static byte array
                encryptedData = ms.ToArray();
                return Convert.ToBase64String(encryptedData);
            }
        }
    }

    // Method to decrypt data
    public static string Decrypt(string ciphertext, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)

            // Create a decryptor to perform the stream transform
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            // Create the streams used for decryption
            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }
    }
}
Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Friend Class Program
	' Declare a static byte array for encrypted data
	Public Shared encryptedData() As Byte

	' Main method to demonstrate encryption and decryption
	Public Shared Sub Main(ByVal args() As String)
		' String plaintext to be encrypted
		Dim plaintext As String = "This is some sensitive data!"
		Dim key As String = "abcdefghijklmnop" ' 128-bit key (16 characters)

		' Encrypt the plaintext
		Dim ciphertext As String = Encrypt(plaintext, key)
		Console.WriteLine("Encrypted Data: " & ciphertext)

		' Decrypt the ciphertext
		Dim decryptedData As String = Decrypt(ciphertext, key)
		Console.WriteLine("Decrypted Data: " & decryptedData)
	End Sub

	' Method to encrypt data
	Public Shared Function Encrypt(ByVal plaintext As String, ByVal key As String) As String
		' Create a new instance of the AES encryption algorithm
		Using aes As Aes = System.Security.Cryptography.Aes.Create()
			aes.Key = Encoding.UTF8.GetBytes(key)
			aes.IV = New Byte(15){} ' Initialization vector (IV)

			' Create an encryptor to perform the stream transform
			Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)

			' Create the streams used for encryption
			Using ms As New MemoryStream()
				' Create a CryptoStream using the encryptor
				Using cs As New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
					Using sw As New StreamWriter(cs)
						sw.Write(plaintext)
					End Using
				End Using
				' Store the encrypted data in the public static byte array
				encryptedData = ms.ToArray()
				Return Convert.ToBase64String(encryptedData)
			End Using
		End Using
	End Function

	' Method to decrypt data
	Public Shared Function Decrypt(ByVal ciphertext As String, ByVal key As String) As String
		Using aes As Aes = System.Security.Cryptography.Aes.Create()
			aes.Key = Encoding.UTF8.GetBytes(key)
			aes.IV = New Byte(15){} ' Initialization vector (IV)

			' Create a decryptor to perform the stream transform
			Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)

			' Create the streams used for decryption
			Using ms As New MemoryStream(Convert.FromBase64String(ciphertext))
				Using cs As New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
					Using sr As New StreamReader(cs)
						Return sr.ReadToEnd()
					End Using
				End Using
			End Using
		End Using
	End Function
End Class
$vbLabelText   $csharpLabel

C# AES Encryption (How It Works For Developers):圖 1 - 使用記憶體串流進行加密和解密輸出

程式碼說明

  1. Aes.Create():這將建立一個新的 AES 加密演算法實例。
  2. aes.Key:用於加密和解密的金鑰。 它必須是有效的大小,例如 128 位元組(16 位元組)、192 位元組或 256 位元組。
  3. aes.IV:初始化向量 (IV) 用於隨機化加密過程。 在本範例中,為了簡單起見,我們使用零的 IV。
  4. MemoryStream:這使我們能夠以位元組流的形式處理加密資料。
  5. CryptoStream:它轉換資料流(加密或解密)。

進階範例:使用自訂金鑰和 IV 的 AES 加密。

讓我們在前一個範例的基礎上,產生 隨機金鑰IV,確保加密更加安全。

public static string EncryptData(string plaintext)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = new byte[32]; // AES-256 requires a 256-bit key (32 bytes)
        aes.IV = new byte[16];  // 128-bit block size

        // Randomly generate key and IV
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(aes.Key); // Generate a random key
            rng.GetBytes(aes.IV);  // Generate a random IV
        }

        // Create an encryptor to perform the stream transform
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        // Create the streams used for encryption
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(plaintext);
                }
            }
            return Convert.ToBase64String(ms.ToArray());
        }
    }
}
public static string EncryptData(string plaintext)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = new byte[32]; // AES-256 requires a 256-bit key (32 bytes)
        aes.IV = new byte[16];  // 128-bit block size

        // Randomly generate key and IV
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(aes.Key); // Generate a random key
            rng.GetBytes(aes.IV);  // Generate a random IV
        }

        // Create an encryptor to perform the stream transform
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        // Create the streams used for encryption
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(plaintext);
                }
            }
            return Convert.ToBase64String(ms.ToArray());
        }
    }
}
Public Shared Function EncryptData(ByVal plaintext As String) As String
	Using aes As Aes = Aes.Create()
		aes.Key = New Byte(31){} ' AES-256 requires a 256-bit key (32 bytes)
		aes.IV = New Byte(15){} ' 128-bit block size

		' Randomly generate key and IV
		Using rng As RandomNumberGenerator = RandomNumberGenerator.Create()
			rng.GetBytes(aes.Key) ' Generate a random key
			rng.GetBytes(aes.IV) ' Generate a random IV
		End Using

		' Create an encryptor to perform the stream transform
		Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)

		' Create the streams used for encryption
		Using ms As New MemoryStream()
			Using cs As New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
				Using sw As New StreamWriter(cs)
					sw.Write(plaintext)
				End Using
			End Using
			Return Convert.ToBase64String(ms.ToArray())
		End Using
	End Using
End Function
$vbLabelText   $csharpLabel

在這種情況下,每次呼叫函式時,我們都會產生 new keyIV。 這可提供更強大的加密功能,因為每次操作都未使用 相同的金鑰AES 支援 128、192 和 256 位元等金鑰大小

使用 AES 解密資料

解密是加密資料的逆向過程。 在我們的範例中,必須提供用於加密的相同金鑰和 IV 來解密資料。 解密過程包括將加密資料轉換回原始形式。

以下是使用先前加密資料的範例:

public static string DecryptData(string ciphertext, byte[] key, byte[] iv)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = key;
        aes.IV = iv;

        // Create a decryptor to perform the stream transform
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        // Create the streams used for decryption
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
        {
            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader sr = new StreamReader(cs))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}
public static string DecryptData(string ciphertext, byte[] key, byte[] iv)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = key;
        aes.IV = iv;

        // Create a decryptor to perform the stream transform
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        // Create the streams used for decryption
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ciphertext)))
        {
            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader sr = new StreamReader(cs))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}
Public Shared Function DecryptData(ByVal ciphertext As String, ByVal key() As Byte, ByVal iv() As Byte) As String
	Using aes As Aes = Aes.Create()
		aes.Key = key
		aes.IV = iv

		' Create a decryptor to perform the stream transform
		Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)

		' Create the streams used for decryption
		Using ms As New MemoryStream(Convert.FromBase64String(ciphertext))
			Using cs As New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
				Using sr As New StreamReader(cs)
					Return sr.ReadToEnd()
				End Using
			End Using
		End Using
	End Using
End Function
$vbLabelText   $csharpLabel

此代碼可將 加密資料解密回 原始資料

具有 AES 加密功能的 IronPDF.

IronPDF for .NET 是一個簡單且適合開發人員使用的 .NET 函式庫,可使用簡單的 C# 程式碼來產生、編輯和處理 PDF。 它允許開發人員 直接從 HTML、CSS 和 JavaScript 建立 PDF 文件,這對於動態產生報表、發票或其他文件非常有用。 IronPDF 支援合併、分割,甚至新增密碼或數位簽章等安全功能,是在 .NET 應用程式中產生 PDF 的全面解決方案。

整合 IronPDF 與 AES 加密。

C# AES Encryption (How It Works For Developers):圖 2 - IronPDF

當您產生敏感的報告或文件時,您可能需要確保這些 PDF 內的資料在分享前已加密。 AES(進階加密標準)加密是安全加密 PDF 檔案內容的完美解決方案。 透過結合 IronPDF 與 AES 加密,您可以保護 PDF 內的資料,同時保持處理文件本身的能力。

步驟 1:使用 IronPDF 建立 PDF。

使用 ChromePdfRenderer 類別從 HTML 內容產生 PDF 並將其儲存至檔案:

var htmlContent = "<h1>Confidential</h1><p>This is sensitive data.</p>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs(@"C:\Reports\ConfidentialReport.pdf");
var htmlContent = "<h1>Confidential</h1><p>This is sensitive data.</p>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs(@"C:\Reports\ConfidentialReport.pdf");
Dim htmlContent = "<h1>Confidential</h1><p>This is sensitive data.</p>"
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("C:\Reports\ConfidentialReport.pdf")
$vbLabelText   $csharpLabel

步驟 2:使用 AES 加密 PDF

PDF檔案建立完成後,使用AES演算法加密:

byte[] pdfBytes = File.ReadAllBytes(@"C:\Reports\ConfidentialReport.pdf");
using (Aes aes = Aes.Create())
{
    aes.Key = Encoding.UTF8.GetBytes("abcdefghijklmnop");
    aes.IV = new byte[16];
    using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(pdfBytes, 0, pdfBytes.Length);
        }
        File.WriteAllBytes(@"C:\Reports\ConfidentialReport.encrypted", ms.ToArray());
    }
}
byte[] pdfBytes = File.ReadAllBytes(@"C:\Reports\ConfidentialReport.pdf");
using (Aes aes = Aes.Create())
{
    aes.Key = Encoding.UTF8.GetBytes("abcdefghijklmnop");
    aes.IV = new byte[16];
    using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(pdfBytes, 0, pdfBytes.Length);
        }
        File.WriteAllBytes(@"C:\Reports\ConfidentialReport.encrypted", ms.ToArray());
    }
}
Dim pdfBytes() As Byte = File.ReadAllBytes("C:\Reports\ConfidentialReport.pdf")
Using aes As Aes = Aes.Create()
	aes.Key = Encoding.UTF8.GetBytes("abcdefghijklmnop")
	aes.IV = New Byte(15){}
	Using encryptor = aes.CreateEncryptor(aes.Key, aes.IV)
	Using ms = New MemoryStream()
		Using cs = New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
			cs.Write(pdfBytes, 0, pdfBytes.Length)
		End Using
		File.WriteAllBytes("C:\Reports\ConfidentialReport.encrypted", ms.ToArray())
	End Using
	End Using
End Using
$vbLabelText   $csharpLabel

結論

C# AES Encryption (How It Works For Developers):圖 3 - 授權

將 IronPDF 與 AES 加密技術整合,可讓您產生既可存取又可加密的動態安全文件。 無論是開發需要安全文件產生或管理敏感報告的應用程式,結合 IronPDF 與穩固的加密功能都能保護您的資料。 IronPDF 簡化了 PDF 的工作,而 AES 則保證了內容的安全性。

IronPDF 提供 免費試用,讓開發人員在投入使用前輕鬆探索其功能。 如果您準備將 IronPDF 整合到您的專案中,一次性購買的授權價格從 $999 起。

常見問題解答

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字符串轉換為 PDF。您還可以使用 RenderHtmlFileAsPdf 將 HTML 文件轉換為 PDF。

什麼是 AES 加密,並且如何在 C# 中使用它?

AES(Advanced Encryption Standard)是一種用於保護數據的對稱加密算法。在 C# 中,AES 加密使用 System.Security.Cryptography 命名空間中的 AES 類來實現。您需要創建一個 AES 實例,設置鍵和值 (IV) 參數,然後使用 ICryptoTransform 接口來加密和解密數據。

使用密碼分組鏈 (CBC) 模式在 AES 加密中的好處是什麼?

密碼分組鏈 (CBC) 模式通過確保相同的明文分組生成不同的密文分組來增強安全性。這是透過使用初始化向量 (IV) 來鏈接分組的加密達成的。

如何在 C# 中使用 AES 加密 PDF 文件?

要在 C# 中使用 AES 加密 PDF,您可以利用 IronPDF 來處理 PDF 文件,然後透過加密 PDF 位元組來應用 AES 加密,使用指定的金鑰和初始化向量,然後將加密後的數據寫回到新文件中。

在 C# 應用程式中實現 AES 加密包括哪些步驟?

要在 C# 中實現 AES 加密,您需要創建一個 AES 實例,設置金鑰和初始化向量,創建加密器,然後使用 MemoryStreamCryptoStream 來轉換數據。

我可以在 C# 中為 AES 加密使用自定義金鑰和初始化向量嗎?

可以,在 AES 加密中,您可以指定自定義的金鑰和初始化向量以提高安全性。建議為每次加密會話生成隨機值以獲得更好的保護。

開發者如何在 C# 中增強 PDF 文件的安全性?

開發者可以使用 IronPDF 與 AES 加密相結合來增強 C# 中 PDF 文件的安全性,這樣可以創建、編輯和保護 PDF,包括添加密碼和數字簽名。

IronPDF 如何幫助在分享之前保護 PDF 內容?

IronPDF 幫助在分享前保護 PDF 內容,方法是允許開發者使用 AES 加密 PDF。此過程包括使用加密方法生成、編輯和處理 PDF 文件,以確保數據保護。

為何金鑰管理在 AES 加密中是重要的?

金鑰管理在 AES 加密中至關重要,因為加密數據的安全性在很大程度上取決於加密金鑰的保密性和強度。適當的管理可以防止未經授權的訪問。

IronPDF 庫為 C# 開發者提供了哪些關鍵功能?

IronPDF 庫允許 C# 開發者輕鬆地創建、編輯和操作 PDF 文件。它支持合併、拆分和使用加密進行 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 小時在線上。
聊天
電子郵件
打電話給我