In this article, we are going to learn how to encrypt and decrypt file data using a key in .NET 5.
What is encryption?
Encryption is the process of taking plain text and convert it into an unreadable format — called ciphertext. This helps protect the confidentiality of digital data either stored on computer systems or transmitted through a network like the internet.
What is decryption?
Decryption is the process of taking ciphertext and convert it into a readable format — called plaintext.
We use the same key to encrypt the data and with the same key, we can decrypt the data, which means a single key is required for encryption and decryption.
Let us understand it with an example.
Prerequisites
First, open Visual Studio 2019 and create a .NET 5 application.
Create AesOperation class and pass the below code.
public class AesOperation { private readonly static string key = "b14ca5898a4e4133bbce2ea2315a1916"; public static string EncryptString(string plainText) { byte[] iv = new byte[16]; byte[] array; using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write)) { using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream)) { streamWriter.Write(plainText); } array = memoryStream.ToArray(); } } } return Convert.ToBase64String(array); } public static string DecryptString(string cipherText) { byte[] iv = new byte[16]; byte[] buffer = Convert.FromBase64String(cipherText); using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream memoryStream = new MemoryStream(buffer)) { using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read)) { using (StreamReader streamReader = new StreamReader((Stream)cryptoStream)) { return streamReader.ReadToEnd(); } } } } } }
Create a function and paste the below code.
public static void SavefileData() { var inputFile = @"place your path"; //root folder of your project var outputFile = Path.Combine(_env.ContentRootPath, "wwwroot", "upload", "demo.txt"); //Read the contain for file var plainText = File.ReadAllText(inputFile); //Encrypt plain text var encryptString = AesOperation.EncryptString(plainText); //Decrypt plain text var dencryptedString = AesOperation.DecryptString(encryptString); //store it root folder File.WriteAllTextAsync(outputFile, dencryptedString); }
In the below image you can see the encrypted text of the file.
Conclusion
This article taught us how to use a key for encryption and decryption in .Net 5. As per our requirement, we can also use different types of methods present inside the Aes Class.
Also, Check Basic Authentication In .NET Core 5.0