.NET幫助 C# AES加密(對開發者如何理解的工作) Jacob Mellor 更新:2026年2月1日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 AES (高級加密標準) 是最常用的對稱加密算法之一。 它使用相同的密鑰來加密和解密數據,使得AES加密在許多應用程序中能夠高效快速地保護敏感數據。 本教程將重點介紹C#中的AES加密,使用AES類來加密和解密數據以及IronPDF Library。 我們將涵蓋實用例子,走過加密過程,並了解如何使用密碼區塊鏈接(CBC)模式來提高安全性。 我們還將討論加密密鑰管理和初始化向量(IV)的角色。 Introduction of AES Encryption in C 高級加密標準(AES)是一種由國家標準和技術研究所(NIST)標準化的對稱加密算法。 該算法可以有128、192或256位的密鑰大小,非常適合用於加密機密數據。 它使用相同的加密密鑰來加密和解密數據。 AES通過將原始數據分成區塊並在這些區塊上應用變換來工作。 它以不同的密碼模式運行,如CBC(密碼區塊鏈接)和電子代碼本(ECB),每個都提供不同的安全功能。 How AES Works in C 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),用於隨機化加密過程。 在此示例中,為簡便起見,我們使用全零IV。 MemoryStream: 這允許我們以字節流的形式處理加密數據。 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 在這種情況下,每次調用函數時,我們會生成新密鑰和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(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 實例,設置金鑰和初始化向量,創建加密器,然後使用 MemoryStream 和 CryptoStream 來轉換數據。 我可以在 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 立即與工程團隊聊天 首席技術官 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技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C#嘗試-捕捉-最終區塊(對開發者如何理解的工作)C# HttpClient (如何為開發人...
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多