.NET HELP C# AES Encryption (How It Works For Developers) Jacob Mellor 更新:2025年7月28日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 AES(高級加密標準)是最常用的對稱加密演算法之一。 它使用同一個金鑰對資料進行加密和解密,因此 AES 加密高效快速,適用於保護許多應用程式中的敏感資料。 本教學將重點放在 C# 中的 AES 加密,使用 AES 類別對資料進行加密和解密,以及IronPDF 庫。 我們將介紹實際範例,逐步講解加密過程,並了解如何使用密碼塊連結 (CBC) 模式來提高安全性。 我們也將討論加密金鑰管理以及初始化向量(IV)的作用。 C# 中 AES 加密的引入 高級加密標準 (AES) 是由美國國家標準與技術研究院 (NIST) 制定的對稱加密演算法。 此演算法的金鑰長度可以是 128 位元、192 位元或 256 位元,對於加密機密資料具有很高的安全性。 它使用相同的加密金鑰對資料進行加密和解密。 AES 的工作原理是將原始資料分割成區塊,然後對這些區塊套用轉換。 它採用不同的加密模式,例如 CBC(密碼塊連結)和電子密碼本 (ECB),每種模式都提供不同的安全特性。 C# 中的 AES 工作原理 C# 中的 AES 加密演算法是 System.Security.Cryptography 命名空間的一部分。 這個命名空間包含 AES 類,讓我們可以建立 AES 實例,指定金鑰大小、密碼模式和填滿模式,然後使用金鑰對資料進行加密和解密。 若要在 C# 中使用 AES,請依照下列基本步驟操作: 使用Aes.Create()建立 AES 類別的實例。 設定金鑰、初始化向量 (IV) 和其他相關參數,如加密模式。 使用 ICryptoTransform 介面加密資料並將其寫入 MemoryStream。 使用相同的金鑰和 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 加密(開發者如何運作):圖 1 - 使用記憶體流進行加密和解密輸出 程式碼解釋 Aes.Create() :這將建立一個新的 AES 加密演算法實例。 aes.Key :用於加密和解密的金鑰。 它必須是有效大小,例如 128 位元(16 位元組)、192 位元或 256 位元。 aes.IV :初始化向量(IV)用於隨機化加密過程。 為了簡單起見,本例中使用零作為隱含波動率。 MemoryStream:這使我們能夠以位元組流的形式處理加密資料。 CryptoStream:它轉換資料流(加密或解密)。 進階範例:使用自訂金鑰和初始化向量的 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 在這種情況下,每次呼叫函數時,我們都會產生一個新的金鑰和初始化向量 (IV) 。 這樣可以提供更強大的加密,因為每個操作都不會使用同一個金鑰。 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 這段程式碼將加密資料解密回原始資料。 IronPDF 與 AES 加密 IronPDF 是一個簡單易用的 .NET 程式庫,旨在透過簡單的 C# 程式碼產生、編輯和操作 PDF 檔案。 它允許開發人員直接從 HTML、CSS 和 JavaScript 建立 PDF 文檔,這對於動態生成報告、發票或其他文檔非常有用。 IronPDF 支援合併、拆分,甚至添加密碼或數位簽章等安全功能,是 .NET 應用程式中產生 PDF 的綜合解決方案。 將 IronPDF 與 AES 加密集成 C# AES 加密(開發者如何理解其工作原理):圖 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 加密(開發者如何理解):圖 3 - 許可 將 IronPDF 與 AES 加密集成,可以產生動態、安全的文檔,這些文檔既可存取又可加密。 無論是開發需要安全產生文件的應用程序,還是管理敏感報告,將 IronPDF 與可靠的加密技術相結合都能保護您的資料。 IronPDF 簡化了 PDF 的處理,而 AES 則保證了內容的安全。 IronPDF 提供免費試用,方便開發者在正式購買前探索其各項功能。 如果您準備將 IronPDF 整合到您的專案中,一次性購買授權的價格從$799起。 常見問題解答 如何在 C# 中將 HTML 轉換為 PDF? 您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換成 PDF。您也可以使用 RenderHtmlFileAsPdf 將 HTML 檔案轉換成 PDF。 什麼是 AES 加密,在 C# 中如何使用? AES(進階加密標準)是一種用於保護資料安全的對稱加密演算法。在 C# 中,AES 加密是使用 System.Security.Cryptography 命名空間中的 AES 類來實作的。您可以建立 AES 範例、設定金鑰和 IV 參數,並使用 ICryptoTransform 介面來加密和解密資料。 在 AES 加密中使用 Cipher Block Chaining (CBC) 模式有什麼好處? Cipher Block Chaining (CBC) 模式透過確保相同的明文區塊產生不同的密文區塊來增強安全性。這是透過使用初始化向量 (IV) 來鏈結加密區塊來實現的。 如何在 C# 中使用 AES 加密 PDF 文件? 要在 C# 中使用 AES 加密 PDF,您可以利用 IronPDF 來處理 PDF 檔案,然後應用 AES 加密,方法是先使用指定的金鑰和 IV 加密 PDF 位元組,再將加密資料寫回新檔案。 在 C# 應用程式中實作 AES 加密涉及哪些步驟? 要在 C# 中實作 AES 加密,您需要建立 AES 範例、設定金鑰和 IV、建立加密器,並使用 MemoryStream 和 CryptoStream 來轉換資料。 我可以在 C# 中使用自訂金鑰和 IV 進行 AES 加密嗎? 是的,在 AES 加密中,您可以指定自訂金鑰和 IV 來加強安全性。建議為每個加密階段產生隨機值,以獲得更好的保護。 開發人員如何在 C# 中加強 PDF 文件的安全性? 開發人員可以使用 IronPDF 結合 AES 加密來增強 C# 中 PDF 文件的安全性,允許創建、編輯和保護 PDF,包括添加密碼和數位簽名。 IronPDF 如何在分享前保護 PDF 內容的安全? IronPDF 可讓開發人員使用 AES 加密 PDF,有助於在分享之前保護 PDF 內容的安全。這個過程包括使用加密方法產生、編輯和操作 PDF 檔案,以確保資料受到保護。 為什麼金鑰管理在 AES 加密中很重要? 金鑰管理在 AES 加密中至關重要,因為加密資料的安全性在很大程度上取決於加密金鑰的保密性和強度。適當的管理可防止未經授權的存取。 適用於 C# 開發人員的 IronPDF 函式庫有哪些主要功能? IronPDF 函式庫可讓 C# 開發人員輕鬆建立、編輯和處理 PDF 文件。它支援的功能包括合併、分割,以及以加密來保護 PDF,強化文件管理與安全性。 Jacob Mellor 立即與工程團隊聊天 首席技術長 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 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 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. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 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 閱讀更多 C# try catch finally (How It Works For Developers)C# HttpClient (How It Works For Dev...
更新2025年12月11日 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. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 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 閱讀更多