Secure String Encryption and Decryption in C# with AES Algorithm

Introduction

In today's digital age, data security is paramount. Whether it's protecting user passwords, financial information, or any other sensitive data, encryption is a fundamental tool for safeguarding information from unauthorized access. In this blog post, we'll explore how to implement secure string encryption and decryption in C# using the Advanced Encryption Standard (AES) algorithm with .NET Core.

Understanding AES Encryption

AES is a symmetric encryption algorithm widely used for securing data. It operates on blocks of data and supports key lengths of 128, 192, and 256 bits. In our implementation, we'll focus on AES with a 256-bit key, which provides a high level of security.

Setting Up the .NET Core Project

Let's start by setting up a new .NET Core project. Open your preferred development environment and create a new console application:

dotnet new console -n StringEncryptionDemo
cd StringEncryptionDemo

Implementing Encryption and Decryption Logic

Next, we'll implement the logic for encrypting and decrypting strings using AES. Create a class named StringEncryptor:

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

public class StringEncryptor
{
    private readonly byte[] key;
    private readonly byte[] iv;

    public StringEncryptor(string keyString, string ivString)
    {
        key = Encoding.UTF8.GetBytes(keyString);
        iv = Encoding.UTF8.GetBytes(ivString);
    }

    public string Encrypt(string plainText)
    {
        using var aes = Aes.Create();
        aes.Key = key;
        aes.IV = iv;

        var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        using var memoryStream = new MemoryStream();
        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            using (var streamWriter = new StreamWriter(cryptoStream))
            {
                streamWriter.Write(plainText);
            }
        }

        return Convert.ToBase64String(memoryStream.ToArray());
    }

    public string Decrypt(string cipherText)
    {
        using var aes = Aes.Create();
        aes.Key = key;
        aes.IV = iv;

        var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        using var memoryStream = new MemoryStream(Convert.FromBase64String(cipherText));
        using var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        using var streamReader = new StreamReader(cryptoStream);

        return streamReader.ReadToEnd();
    }
}

Putting it All Together

Now, let's use our StringEncryptor class to encrypt and decrypt strings:

class Program
{
    static void Main(string[] args)
    {
        string key = "ThisIsASuperSecretKey";
        string iv = "ThisIsASuperSecretIV";

        StringEncryptor encryptor = new StringEncryptor(key, iv);

        string originalString = "Hello, world!";
        Console.WriteLine("Original: " + originalString);

        string encryptedString = encryptor.Encrypt(originalString);
        Console.WriteLine("Encrypted: " + encryptedString);

        string decryptedString = encryptor.Decrypt(encryptedString);
        Console.WriteLine("Decrypted: " + decryptedString);
    }
}

Conclusion

In this blog, we've embarked on a journey through the realm of data security, focusing on implementing secure string encryption and decryption in C# with the Advanced Encryption Standard (AES) algorithm and .NET Core. By leveraging AES, a robust symmetric encryption algorithm, we've empowered ourselves to protect sensitive data from prying eyes.