Zum Fußzeileninhalt springen
.NET HILFE

C# AES-Verschlüsselung (Wie es für Entwickler funktioniert)

AES (Advanced Encryption Standard) is one of the most commonly used symmetric encryption algorithms. It uses the same key to encrypt and decrypt data, making AES encryption efficient and fast for securing sensitive data in many applications.

This tutorial will focus on AES encryption in C#, using the AES class to encrypt and decrypt data and IronPDF Library. We’ll cover practical examples, walk through the encryption process, and see how to use Cipher Block Chaining (CBC) mode to increase security. We’ll also discuss encryption key management and the role of the initialization vector (IV).

Introduction of AES Encryption in C\

Advanced Encryption Standard (AES) is a symmetric encryption algorithm standardized by the National Institute of Standards and Technology (NIST). The algorithm can have key sizes of 128, 192, or 256 bits and is highly secure for encrypting confidential data. It uses the same encryption key to encrypt and decrypt data.

AES works by splitting the original data into blocks and applying transformations on those blocks. It operates in different cipher modes, such as CBC (Cipher Block Chaining) and Electronic CodeBook (ECB), each providing different security features.

How AES Works in C\

The AES encryption algorithm in C# is part of the System.Security.Cryptography namespace. This namespace includes the AES class, which allows us to create an instance of AES, specify the key size, cipher mode, and padding mode, and then encrypt and decrypt data using a secret key.

To use AES in C#, follow these basic steps:

  1. Create an instance of the AES class using Aes.Create().
  2. Set the key, IV, and other relevant parameters like cipher mode.
  3. Encrypt the data using the ICryptoTransform interface and write it to a MemoryStream.
  4. Decrypt the data using the same key and IV.

Let’s create a basic encryption process and decryption program in 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 Encryption (How It Works For Developers): Figure 1 - Encryption and Decryption Output using Memory Stream

Explanation of Code

  1. Aes.Create(): This creates a new instance of the AES encryption algorithm.
  2. aes.Key: The key used for both encryption and decryption. It must be of a valid size, such as 128 bits (16 bytes), 192 bits, or 256 bits.
  3. aes.IV: The initialization vector (IV), is used to randomize the encryption process. In this example, we use an IV of zeros for simplicity.
  4. MemoryStream: This allows us to work with the encrypted data as a stream of bytes.
  5. CryptoStream: It transforms the data stream (encryption or decryption).

Advanced Example: AES Encryption with Custom Key and IV

Let’s build upon the previous example by generating a random key and IV, ensuring the encryption is more secure.

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

In this case, we generate a new key and IV each time the function is called. This provides more robust encryption as the same key is unused for every operation. AES supports key sizes such as 128, 192, and 256 bits.

Decrypting Data with AES

Decryption is the reverse process to encrypt data. In our examples, the same key and IV used for encryption must be provided to decrypt the data. The decryption process involves converting the encrypted data back into its original form.

Here’s an example that uses the previously encrypted data:

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

This code decrypts the encrypted data back into the original data.

IronPDF with AES Encryption

IronPDF is a simple and developer-friendly .NET library designed to generate, edit, and manipulate PDFs using simple C# code. It allows developers to create PDF documents directly from HTML, CSS, and JavaScript, which can be incredibly useful for dynamically generating reports, invoices, or other documents. With support for merging, splitting, and even adding security features like passwords or digital signatures, IronPDF is a comprehensive solution for PDF generation in .NET applications.

Integrating IronPDF with AES Encryption

C# AES Encryption (How It Works For Developers): Figure 2 - IronPDF

When you generate sensitive reports or documents, you may need to ensure the data within those PDFs is encrypted before sharing. AES (Advanced Encryption Standard) encryption is a perfect solution for securely encrypting the contents of PDF files. By combining IronPDF and AES encryption, you can protect the data within your PDFs while maintaining the ability to work with the document itself.

Step 1: Create a PDF Using IronPDF

Use the ChromePdfRenderer class to generate a PDF from HTML content and save it to a file:

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

Step 2: Encrypt the PDF Using AES

Once the PDF is created, encrypt it with 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

Conclusion

C# AES Encryption (How It Works For Developers): Figure 3 - Licensing

Integrating IronPDF with AES encryption allows you to generate dynamic, secure documents that are both accessible and encrypted. Whether developing applications requiring secure document generation or managing sensitive reports, combining IronPDF with solid encryption protects your data. IronPDF simplifies working with PDFs, while AES guarantees that the content remains secure.

IronPDF offers a free trial, making it easy for developers to explore its features before committing. If you’re ready to implement IronPDF into your projects, licenses start at $799 for a one-time purchase.

Häufig gestellte Fragen

Wie kann ich HTML in PDF in C# konvertieren?

Sie können die RenderHtmlAsPdf-Methode von IronPDF verwenden, um HTML-Strings in PDFs zu konvertieren. Sie können auch HTML-Dateien mit RenderHtmlFileAsPdf in PDFs konvertieren.

Was ist AES-Verschlüsselung und wie wird sie in C# verwendet?

AES (Advanced Encryption Standard) ist ein symmetrischer Verschlüsselungsalgorithmus zur Sicherung von Daten. In C# wird die AES-Verschlüsselung mit der AES-Klasse aus dem Namespace System.Security.Cryptography implementiert. Sie erstellen eine AES-Instanz, setzen die Schlüssel- und IV-Parameter und verwenden die ICryptoTransform-Schnittstelle zur Verschlüsselung und Entschlüsselung von Daten.

Welche Vorteile bietet der Cipher Block Chaining (CBC)-Modus bei der AES-Verschlüsselung?

Der Cipher Block Chaining (CBC)-Modus erhöht die Sicherheit, indem er sicherstellt, dass identische Klartextblöcke unterschiedliche Chiffretextblöcke erzeugen. Dies wird durch die Verwendung eines Initialisierungsvektors (IV) zur Verknüpfung der Blockverschlüsselungen erreicht.

Wie kann ich ein PDF-Dokument mit AES in C# verschlüsseln?

Um ein PDF mit AES in C# zu verschlüsseln, kann man IronPDF verwenden, um die PDF-Datei zu bearbeiten und dann die AES-Verschlüsselung anwenden, indem man die PDF-Bytes mit einem angegebenen Schlüssel und IV verschlüsselt, bevor man die verschlüsselten Daten in eine neue Datei schreibt.

Welche Schritte sind erforderlich, um AES-Verschlüsselung in einer C#-Anwendung zu implementieren?

Um AES-Verschlüsselung in C# zu implementieren, müssen Sie eine AES-Instanz erstellen, den Schlüssel und IV festlegen, einen Verschlüsseler erstellen und MemoryStream sowie CryptoStream verwenden, um die Daten zu transformieren.

Kann ich einen benutzerdefinierten Schlüssel und IV für AES in C# verwenden?

Ja, bei der AES-Verschlüsselung können Sie einen benutzerdefinierten Schlüssel und IV angeben, um die Sicherheit zu erhöhen. Es wird empfohlen, für jede Verschlüsselungssitzung zufällige Werte zu generieren, um den Schutz zu verbessern.

Wie können Entwickler die Sicherheit von PDF-Dokumenten in C# verbessern?

Entwickler können IronPDF in Kombination mit der AES-Verschlüsselung verwenden, um die Sicherheit von PDF-Dokumenten in C# zu verbessern, wodurch das Erstellen, Bearbeiten und Sichern von PDFs, einschließlich dem Hinzufügen von Passwörtern und digitalen Signaturen, ermöglicht wird.

Wie hilft IronPDF beim Sichern von PDF-Inhalten vor der Freigabe?

IronPDF hilft beim Sichern von PDF-Inhalten vor der Freigabe, indem es Entwicklern ermöglicht, PDFs mit AES zu verschlüsseln. Dieser Prozess umfasst das Generieren, Bearbeiten und Manipulieren von PDF-Dateien mit Verschlüsselungsmethoden, um den Datenschutz zu gewährleisten.

Warum ist Schlüsselverwaltung bei der AES-Verschlüsselung wichtig?

Die Schlüsselverwaltung ist bei der AES-Verschlüsselung entscheidend, da die Sicherheit der verschlüsselten Daten stark von der Geheimhaltung und Stärke des Verschlüsselungsschlüssels abhängt. Eine ordnungsgemäße Verwaltung verhindert unbefugten Zugriff.

Was sind die Hauptmerkmale der IronPDF-Bibliothek für C#-Entwickler?

Die IronPDF-Bibliothek ermöglicht es C#-Entwicklern, einfach PDF-Dokumente zu erstellen, zu bearbeiten und zu manipulieren. Sie unterstützt Funktionen wie das Zusammenführen, Aufteilen und Sichern von PDFs mit Verschlüsselung und verbessert die Dokumentenverwaltung und -sicherheit.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen