跳至頁尾內容
開發者更新

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

AES (高級加密標準) 是最常用的對稱加密演算法之一。 它使用相同的金鑰來加密和解密資料,使得AES加密在許多應用中對保護敏感資料既高效又快速。

本教程將著重於C#中的AES加密,使用AES類來加密和解密資料以及IronPDF程式庫。 我們將涵蓋實用範例,演練加密過程,並了解如何使用密碼分組鏈(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,請依照這些基本步驟:

  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加密(開發人員如何使用):圖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

在這種情況下,每次調用該函式時,我們都會生成一個新金鑰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,授權從$999起,一次性購買。

常見問題

如何在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字節,再將加密資料寫回新文件中。

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

在C#中實現AES加密,您需要建立AES實例,設置金鑰和IV,建立加密器,並使用MemoryStreamCryptoStream來轉換資料。

我可以在C#的AES加密中使用自定義金鑰和IV嗎?

可以,在AES加密中,您可以指定自定義金鑰和IV來增強安全性。建議為每次加密會話生成隨機值以獲得更好的防護。

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

開發人員可以使用IronPDF與AES加密結合來增強C#中的PDF文件安全性,從而進行PDF建立、編輯和保護,包括新增密碼和數位簽章。

IronPDF如何幫助保護PDF內容以便分享?

IronPDF可幫助在分享之前保護PDF內容,允許開發人員使用AES加密PDF。此過程涉及生成、編輯和操作PDF文件的加密方法,以確保資料保護。

為什麼在AES加密中金鑰管理重要?

在AES加密中,金鑰管理非常重要,因為加密資料的安全性在很大程度上依賴於加密金鑰的保密性和強度。妥善管理可防止未經授權的存取。

對於C#開發人員來說,IronPDF程式庫的主要特點是什麼?

IronPDF程式庫允許C#開發人員輕鬆建立、編輯和操作PDF文件。它支持合併、拆分和加密等功能,增強了文件管理和安全性。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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