.NET 幫助

C# AES 加密(開發者如何使用)

發佈 2024年10月23日
分享:

AES(高級加密標準)是最常用的對稱加密算法之一。 它使用相同的密钥来加密和解密数据,使 AES 加密在许多应用中对保护敏感数据既高效又快速。

本教程將重點介紹在 C# 中的 AES 加密,使用 AES 類別來加密和解密資料,並且IronPDF Library. 我們將涵蓋實用範例,逐步解說加密過程,並了解如何使用密碼區塊鏈接模式。(CBC)模式以提高安全性。 我們還將討論加密金鑰管理和初始化向量的作用(IV).

C# 中的 AES 加密簡介

進階加密標準(AES)是一种由国家标准与技术研究院标准化的对称加密算法(NIST). 該算法可以有128、192或256位的密鑰大小,並且在加密機密數據方面非常安全。 它使用相同的加密密鑰來加密和解密數據。

AES 的運作原理是將原始數據分割成區塊,並對這些區塊進行轉換。 它運行於不同的加密模式,例如 CBC(密碼區塊鏈接)和電子代碼簿(ECB),每個都提供不同的安全功能。

C# 中的 AES 如何工作

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;
    // static void Main
    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);
    }
    public static string Encrypt(string plaintext, string key)
    {
        // AES algorithm
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using (MemoryStream ms = new MemoryStream())
            {
                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);
            }
        }
    }
    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)
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
            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;
    // static void Main
    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);
    }
    public static string Encrypt(string plaintext, string key)
    {
        // AES algorithm
        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = new byte[16]; // Initialization vector (IV)
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using (MemoryStream ms = new MemoryStream())
            {
                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);
            }
        }
    }
    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)
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
            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
	' static void Main
	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
	Public Shared Function Encrypt(ByVal plaintext As String, ByVal key As String) As String
		' AES algorithm
		Using aes As Aes = System.Security.Cryptography.Aes.Create()
			aes.Key = Encoding.UTF8.GetBytes(key)
			aes.IV = New Byte(15){} ' Initialization vector (IV)
			Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)
			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
				' Store the encrypted data in the public static byte array
				encryptedData = ms.ToArray()
				Return Convert.ToBase64String(encryptedData)
			End Using
		End Using
	End Function
	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)
			Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)
			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
VB   C#

C# AES 加密(開發者如何使用):圖 1 - 使用記憶體流的加密和解密輸出

代碼說明

  1. Aes aes = 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
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(aes.Key); // Generate a random key
            rng.GetBytes(aes.IV);  // Generate a random IV
        }
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
        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
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(aes.Key); // Generate a random key
            rng.GetBytes(aes.IV);  // Generate a random IV
        }
        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
        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
		Using rng As RandomNumberGenerator = RandomNumberGenerator.Create()
			rng.GetBytes(aes.Key) ' Generate a random key
			rng.GetBytes(aes.IV) ' Generate a random IV
		End Using
		Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)
		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
VB   C#

在這種情況下,我們每次調用該函數時都生成一個新的密鑰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;
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
        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;
        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
        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
		Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)
		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
VB   C#

此程式碼將加密資料解密回原始資料

IronPDF with AES 加密

IronPDF 是一個簡單且開發者友好的 .NET 函式庫,旨在使用簡單的 C# 代碼生成、編輯和操作 PDF。 它允許開發人員直接從 HTML 創建 PDF 文件,CSS 和 JavaScript,這對於動態生成報告、發票或其他文件非常有用。 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")
VB   C#

步驟 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
VB   C#

結論

C# AES 加密(開發人員如何運作):圖3 - 授權

將IronPDF與AES加密整合,可以生成既可訪問又加密的動態安全文件。 無論是在開發需要安全文件生成的應用程式,還是管理敏感報告,結合 IronPDF 與強大的加密功能都可以保護您的數據。 IronPDF 簡化了處理 PDF 的工作,同時 AES 保證內容的安全性。

IronPDF 提供一個免費試用,讓開發人員在承諾之前輕鬆探索其功能。 如果您準備將IronPDF集成到您的專案中,授權費用從一次性支付$749起。

< 上一頁
C# try catch finally(開發者如何運作)
下一個 >
C# HttpClient(開發人員如何使用)

準備開始了嗎? 版本: 2024.12 剛剛發布

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >