C# AES 加密(開發者如何理解其工作原理)
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();
}
}
}
}
}
}程式碼解釋
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());
}
}
}在這種情況下,每次呼叫函數時,我們都會產生一個新的金鑰和初始化向量 (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();
}
}
}
}
}這段程式碼將加密資料解密回原始資料。
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");步驟 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());
}
}結論
將 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 加密中使用密碼塊連結 (CBC) 模式有哪些好處?
密碼區塊連結 (CBC) 模式透過確保相同的明文區塊產生不同的密文區塊來增強安全性。這是透過使用初始化向量 (IV) 將各個區塊的加密連結起來來實現的。
如何使用 C# 中的 AES 加密 PDF 文件?
若要在 C# 中使用 AES 加密 PDF,您可以利用 IronPDF 處理 PDF 文件,然後使用指定的金鑰和 IV 對 PDF 位元組進行加密,再將加密資料寫回新文件,從而套用 AES 加密。
在 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加密中至關重要,因為加密資料的安全性很大程度上依賴加密金鑰的保密性和強度。妥善管理密鑰可以防止未經授權的存取。
IronPDF 庫對 C# 開發人員有哪些主要功能?
IronPDF庫使C#開發人員能夠輕鬆建立、編輯和操作PDF文件。它支援合併、分割和加密等功能,從而增強文件管理和安全性。







