0% found this document useful (0 votes)
16 views4 pages

C# AES Symmetric Encryption Example

The document provides a C# example of using the System.Security.Cryptography namespace for AES symmetric encryption and decryption. It details the creation of a class that generates a random key and initialization vector (IV), encrypts a plaintext string, and then decrypts it back to the original text. Additionally, it emphasizes security considerations regarding key management and suggests using secure systems for handling encryption keys.

Uploaded by

carewelloman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

C# AES Symmetric Encryption Example

The document provides a C# example of using the System.Security.Cryptography namespace for AES symmetric encryption and decryption. It details the creation of a class that generates a random key and initialization vector (IV), encrypts a plaintext string, and then decrypts it back to the original text. Additionally, it emphasizes security considerations regarding key management and suggests using secure systems for handling encryption keys.

Uploaded by

carewelloman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In

C#, the [Link] namespace provides classes for performing


encryption and decryption. A common and secure method is using symmetric encryption with
the Advanced Encryption Standard (AES) algorithm. Symmetric encryption uses the same
key for both encrypting the plaintext into ciphertext and decrypting the ciphertext back into
plaintext.
Example: AES symmetric encryption
The following is a complete C# example for encrypting and decrypting a string using AES.
The code generates a random key and initialization vector (IV), encrypts the data, and then
decrypts it.
csharp
using System;
using [Link];
using [Link];
using [Link];

public class EncryptionExample


{
// The main method demonstrates the encryption and decryption process
public static void Main()
{
string original = "Here is some confidential data to encrypt.";

// Create an instance of the encryption class


AesOperation aes = new AesOperation();

[Link]($"Original Text: {original}");

// Encrypt the string


string encrypted = [Link](original);
[Link]($"Encrypted Text: {encrypted}");

// Decrypt the string


string decrypted = [Link](encrypted);
[Link]($"Decrypted Text: {decrypted}");
}
}

public class AesOperation


{
// A secret key is required for symmetric encryption.
// In a real application, do not hardcode this key.
// Generate a random key and IV for a new operation.
private readonly byte[] key;
private readonly byte[] iv;

public AesOperation()
{
// Generate a random key and IV for each new instance.
using (Aes aes = [Link]())
{
[Link]();
[Link]();
[Link] = [Link];
[Link] = [Link];
}
}

public string EncryptString(string plainText)


{
// Check arguments for valid data.
if (plainText == null || [Link] <= 0)
throw new ArgumentNullException(nameof(plainText));
if (key == null || [Link] <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || [Link] <= 0)
throw new ArgumentNullException(nameof(iv));

byte[] encrypted;

// Create an Aes object with the specified key and IV.


using (Aes aesAlg = [Link]())
{
[Link] = key;
[Link] = iv;

// Create an encryptor to perform the stream transform.


ICryptoTransform encryptor = [Link]([Link],
[Link]);

// Create the streams used for encryption.


using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor, [Link]))
{
using (StreamWriter swEncrypt = new
StreamWriter(csEncrypt))
{
// Write all data to the stream.
[Link](plainText);
}
encrypted = [Link]();
}
}
}

// Return the encrypted bytes as a Base64 string for easy storage


and transmission.
return Convert.ToBase64String(encrypted);
}

public string DecryptString(string cipherText)


{
// Check arguments for valid data.
if (cipherText == null || [Link] <= 0)
throw new ArgumentNullException(nameof(cipherText));
if (key == null || [Link] <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || [Link] <= 0)
throw new ArgumentNullException(nameof(iv));

// Convert the Base64 string back to byte array.


byte[] cipherBytes = Convert.FromBase64String(cipherText);

string plaintext = null;

// Create an Aes object with the specified key and IV.


using (Aes aesAlg = [Link]())
{
[Link] = key;
[Link] = iv;

// Create a decryptor to perform the stream transform.


ICryptoTransform decryptor = [Link]([Link],
[Link]);

// Create the streams used for decryption.


using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt,
decryptor, [Link]))
{
using (StreamReader srDecrypt = new
StreamReader(csDecrypt))
{
// Read all decrypted data to the end.
plaintext = [Link]();
}
}
}
}
return plaintext;
}
}
Use code with caution.
Explanation of the code

• Symmetric-Key Generation: The AesOperation class generates a new, random 256-


bit key and 128-bit IV when it is instantiated. These are used for both encryption and
decryption.
• Key and IV Management: The key and IV are crucial for the AES algorithm. The
key is the secret for encryption, and the IV is an additional randomization factor that
prevents identical plaintexts from producing identical ciphertexts.
• EncryptString():
o Takes a plaintext string as input.
o Uses [Link]() to get a cryptographic object.
o Creates a MemoryStream and a CryptoStream to perform the encryption.
o Writes the plaintext to the CryptoStream, which encrypts it as it's being
written.
o Converts the resulting encrypted byte array into a Base64 string for safe and
easy handling.
• DecryptString():
o Takes the Base64 ciphertext string as input.
o Converts the Base64 string back into a byte array.
o Creates another set of streams for decryption, using the same key and IV.
o Reads the data from the CryptoStream, which decrypts it as it's read.
o The StreamReader reads the decrypted bytes and returns them as a string.


o

How to use this code


1. Save the file: Save the code as a .cs file, for example, [Link].
2. Compile and run: Compile and run the code from your terminal.

bash

dotnet run

Use code with caution.

• • Expected Output: The program will print the original text, the Base64-encoded
encrypted text, and the final decrypted text, proving that the process was successful.

3.

Security considerations

• Key Security: The most significant security risk is the handling of the key and IV. In
a real-world scenario, you should never hardcode these values or store them in plain
text. Secure key management systems, such as Azure Key Vault or AWS Key
Management Service, should be used instead.
• Asymmetric Encryption: For situations where parties do not share a key beforehand,
or for digital signatures, consider asymmetric encryption using RSA, also found in the
[Link] namespace.

You might also like