.NET 帮助

C# AES 加密(如何为开发人员工作)

乔尔迪·巴尔迪亚
乔尔迪·巴尔迪亚
2024年十月23日
分享:

AES(高级加密标准)是最常用的对称加密算法之一。 它使用相同的密钥对数据进行加密和解密,使得 AES 加密在许多应用程序中都能高效、快速地保护敏感数据的安全。

本教程将重点介绍 C# 中的 AES 加密,使用 AES 类加密和解密数据,以及IronPDF 库. 我们将介绍实际例子,讲解加密过程,并了解如何使用密码块链(CBC)提高安全性的模式。 我们还将讨论加密密钥管理和初始化向量的作用(四).

介绍 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:初始化向量(四)例如,.NET、Java、Python 或 Node.js 是用来随机化加密过程的。 在本示例中,为简单起见,我们使用了零的 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();
                }
            }
        }
    }
}

该代码可将加密数据解密为原始数据

采用 AES 加密技术的 IronPDF

IronPDF for .NET 是一个简单且对开发人员友好的 .NET 库,旨在使用简单的 C# 代码生成、编辑和处理 PDF。 它可以让开发人员直接从 HTML 创建 PDF 文档这些工具包括.NET、Java、Python 或 Node js,对于动态生成报告、发票或其他文档非常有用。 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,为一次性购买。

乔尔迪·巴尔迪亚
乔尔迪·巴尔迪亚
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 运用技能时,他会进行游戏编程。作为产品测试、产品开发和研究的负责人之一,Jordi 为持续的产品改进增添了极大的价值。多样化的经验让他充满挑战和参与感,他说这是他在 Iron Software 工作中最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。
< 前一页
C# try catch finally(开发人员如何使用它)
下一步 >
C# HttpClient(面向开发人员的工作原理)