Encrypting and Decrypting Files using .NET Core

When handling sensitive data in modern applications, the significance of data security cannot be overstressed. From personal details to financial information, securing data against unauthorized access is crucial. This is where file encryption comes into play transforming readable data into an unreadable format and ensuring only those who have the key can decrypt, and therefore access, the original information. In this guide, we're going to deep-dive into how this can effectively be achieved in a .NET Core application through a practical example using AES (Advanced Encryption Standard), currently regarded as one of the most secure encryption algorithms.

Background of the Requirement

The need for secure data handling reiterates across various domains, be it healthcare, finance, or any consumer-based applications. The methodology discussed here was inspired by common scenarios faced by developers integrating security into their software solutions, where the emphasis is on preventing data breaches and ensuring privacy compliance. The approach currently being proposed was constructed to provide hands-on, practical guidance for .NET developers faced with requirements for securing user or business-sensitive data.

Setting Up Your .NET Core Project

Before you start implementing the encryption and decryption logic, make sure that you have .NET Core installed on your system. You can then create a console application which will be our working environment for this task.

dotnet new console -n Codingvila
cd Codingvila

This sets up a basic .NET Core console application.

Using the System.Security.Cryptography Namespace

Encryption and decryption in .NET Core can be accomplished using certain classes found within the System.Security.Cryptography namespace. Add the necessary using directives at the top of your Program.cs file.

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

Why AES for Encryption?

Advanced Encryption Standard (AES) is a symmetric encryption algorithm and a current gold standard for data encryption. This means the same key is used for both encrypting and decrypting data. AES is one of the most widely used encryption standards, and it has been adopted by the U.S. government and other entities worldwide. It is known for its efficiency and robust security. AES uses symmetric key encryption, where the same key is used for both encrypting and decrypting data, which simplifies key management but necessitates secure key sharing or derivation mechanisms.

Encryption

Here's how to implement it.

  1. Generate a Key and Initialization Vector (IV): These are critical for the AES algorithm to perform encryption and must be secure.
  2. Create the Encryptor Object: This object will perform the encryption operation.
  3. Perform Encryption: Read the content from the file to encrypt and write the encrypted result to a new file.

Here is the code for the EncryptFile method which accomplishes this.

public static void EncryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
{
    using (FileStream fileStream = new FileStream(outputFile, FileMode.Create))
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = key;
            aes.IV = iv;

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

            using (CryptoStream cryptoStream = new CryptoStream(fileStream, encryptor, CryptoStreamMode.Write))
            {
                using (FileStream inputFileStream = new FileStream(inputFile, FileMode.Open))
                {
                    inputFileStream.CopyTo(cryptoStream);
                }
            }
        }
    }
}

Decryption

Decryption uses the same key and IV that were used for encryption. Here's the DecryptFile method.

public static void DecryptFile(string inputFile, string outputFile, byte[] key, byte[] iv)
{
    using (FileStream fileStream = new FileStream(outputFile, FileMode.Create))
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = key;
            aes.IV = iv;

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

            using (CryptoStream cryptoStream = new CryptoStream(fileStream, decryptor, CryptoStreamMode.Read))
            {
                using (FileStream outputFileStream = new FileStream(inputFile, FileMode.Open))
                {
                    outputFileStream.CopyTo(cryptoStream);
                }
            }
        }
    }
}

Main Method

You can now utilize these methods in your Main function. Here is a sample demonstration.

static void Main(string[] args)
{
    string originalFile = @"Nikunj_Satasiya.txt";
    string encryptedFile = @"Nikunj_Satasiya_encrypted.txt";
    string decryptedFile = @"Nikunj_Satasiya_decrypted.txt";

    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.GenerateKey();
        aesAlg.GenerateIV();
        byte[] key = aesAlg.Key;
        byte[] iv = aesAlg.IV;

        EncryptFile(originalFile, encryptedFile, key, iv);
        DecryptFile(encryptedFile, decryptedFile, key, iv);
    }

    Console.WriteLine("Encryption and Decryption processes are completed.");
}

Conclusion

Encrypting and decrypting files in .NET Core using AES provides a robust method for securing your data.SENSITIVE_INFORMATION With this basic understanding and the example provided, you can expand it further based on your specific needs to manage security in your applications efficiently.


Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.