Skip to main content

A simple guide to get you started with AES encryption in C#

Using AES (Advanced Encryption Standard) encryption in C# involves several steps, including selecting the appropriate AES variant, handling keys, and implementing encryption and decryption routines. Below is a simple guide to get you started with AES encryption in C#.



1. Choose AES Variant:
   Decide on the AES variant to use (AES-128, AES-192, or AES-256). This choice will determine the key size and the level of security.

2. Create a Key:
   Generate a secure random key of the appropriate size using a cryptographic library. In C#, you can use RNGCryptoServiceProvider for this purpose.

   csharp
   using System.Security.Cryptography;

   byte[] key = new byte[16]; // for AES-128
   using (var rng = new RNGCryptoServiceProvider())
   {
       rng.GetBytes(key);
   }
   

3. Choose a Mode and Padding:
   Decide on the mode of operation (e.g., CBC, GCM) and the padding scheme (e.g., PKCS7). These choices affect how the data is processed during encryption and decryption.

4. Implement Encryption:
   Use the AesManaged class from the System.Security.Cryptography namespace for encryption. Heres a simple example:

   csharp
   using System;
   using System.IO;
   using System.Security.Cryptography;
   using System.Text;

   public class AesEncryption
   {
       public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
       {
           using (AesManaged aesAlg = new AesManaged())
           {
               aesAlg.Key = key;
               aesAlg.IV = iv;

               ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

               using (MemoryStream msEncrypt = new MemoryStream())
               {
                   using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                   {
                       using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                       {
                           swEncrypt.Write(plainText);
                       }
                   }
                   return msEncrypt.ToArray();
               }
           }
       }
   }
   

5. Implement Decryption:
   Implement a similar decryption method using the AesManaged class.

   csharp
   public class AesEncryption
   {
       // ... (previous code)

       public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
       {
           using (AesManaged aesAlg = new AesManaged())
           {
               aesAlg.Key = key;
               aesAlg.IV = iv;

               ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

               using (MemoryStream msDecrypt = new MemoryStream(cipherText))
               {
                   using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                   {
                       using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                       {
                           return srDecrypt.ReadToEnd();
                       }
                   }
               }
           }
       }
   }
   

6. Usage Example:
   Now, you can use the Encrypt and Decrypt methods in your application.

   csharp
   byte[] iv = new byte[16]; // Initialization Vector, should be unique for each encryption
   string plaintext = "Hello, AES!";

   byte[] encrypted = AesEncryption.Encrypt(plaintext, key, iv);
   string decrypted = AesEncryption.Decrypt(encrypted, key, iv);

   Console.WriteLine($"Original: {plaintext}");
   Console.WriteLine($"Encrypted: {Convert.ToBase64String(encrypted)}");
   Console.WriteLine($"Decrypted: {decrypted}");
   

This is a basic guide, and real-world implementations should consider additional security aspects, such as key management and secure random number generation. Always handle encryption keys securely and follow best practices for cryptographic operations.

Comments

Popular posts from this blog

Working with OAuth Tokens in .NET Framework 4.8

  Working with OAuth Tokens in .NET Framework 4.8 OAuth (Open Authorization) is a widely used protocol for token-based authentication and authorization. If you're working with .NET Framework 4.8 and need to integrate OAuth authentication, this guide will walk you through the process of obtaining and using an OAuth token to make secure API requests. Step 1: Understanding OAuth Flow OAuth 2.0 typically follows these steps: The client requests authorization from the OAuth provider. The user grants permission. The client receives an authorization code. The client exchanges the code for an access token. The client uses the token to access protected resources. Depending on your use case, you may be implementing: Authorization Code Flow (for web applications) Client Credentials Flow (for machine-to-machine communication) Step 2: Install Required Packages For handling HTTP requests, install Microsoft.AspNet.WebApi.Client via NuGet: powershell Copy Edit Install-Package Microsoft.AspNet.W...

Changing the Default SSH Port on Windows Server 2019: A Step-by-Step Guide

Changing the Default SSH Port on Windows Server 2019: A Step-by-Step Guide By default, SSH uses port 22 for all connections. However, for enhanced security or due to policy requirements, it may be necessary to change this default port. In this guide, we'll walk you through how to change the SSH port on Windows Server 2019 . Changing the default port not only reduces the chances of brute-force attacks but also minimizes exposure to potential vulnerabilities. Let's get started! Why Change the Default SSH Port? Changing the default SSH port can offer several advantages: Security : Automated scripts often target the default SSH port (22). Changing it can prevent many basic attacks. Compliance : Certain compliance regulations or internal policies may require the use of non-standard ports. Segregation : If multiple services are running on the same server, different ports can be used for easier management and separation. Prerequisites Before proceeding, ensure that you: Have administ...

Understanding SSL Certificate Extensions: PEM vs. CER vs. CRT

Understanding SSL Certificate Extensions: PEM vs. CER vs. CRT In the realm of SSL certificates, file extensions like PEM, CER, and CRT play crucial roles in how cryptographic information is stored and shared. While often used interchangeably, each extension carries its own conventions and encoding formats. In this blog post, we'll unravel the differences between PEM, CER, and CRT to shed light on their individual purposes. PEM (Privacy Enhanced Mail) Format: PEM is a versatile format widely employed for storing cryptographic objects. It utilizes base64-encoded ASCII, often adorned with headers like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----." Extension: Files with the PEM extension are multipurpose, housing certificates, private keys, and other encoded data. Use Case: PEM's flexibility makes it suitable for a variety of cryptographic data, from certificates to private keys and certificate signing requests (CSRs). CER (Certificate) Format...