.NET 幫助

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

Kannaopat Udonpant
坎納帕特·烏頓潘
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();
                    }
                }
            }
        }
    }
}

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());
        }
    }
}

在這種情況下,我們每次調用該函數時都生成一個新的密鑰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();
                }
            }
        }
    }
}

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

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");

步驟 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());
    }
}

結論

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

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

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

Kannaopat Udonpant
坎納帕特·烏頓潘
軟體工程師
在成為軟體工程師之前,Kannapat 在日本北海道大學完成了環境資源博士學位。在攻讀學位期間,Kannapat 也成為了車輛機器人實驗室的成員,該實驗室隸屬於生物生產工程學系。2022 年,他利用自己的 C# 技能,加入了 Iron Software 的工程團隊,專注於 IronPDF 的開發。Kannapat 珍視這份工作,因為他可以直接向負責撰寫大部分 IronPDF 程式碼的開發人員學習。除了同儕學習外,Kannapat 還享受在 Iron Software 工作的社交方面。當他不在撰寫程式碼或文件時,Kannapat 通常會在 PS5 上玩遊戲或重看《最後生還者》。
< 上一頁
C# try catch finally(開發者如何運作)
下一個 >
C# HttpClient(開發人員如何使用)