ASP.NET Encrypt And Decrypt Files Using Advanced Encryption (Rijndael Encryption)

Introduction

The Advanced Encryption Standard (AES), also known as Rijndael Encryption, was developed by two Belgian cryptographers, Vincent Rijmen and Joan Daemen. AES gives a feature to share or store your files in a highly secure manner. In this blog we don’t talk about cryptography or AES, it only explain how to encrypt and decrypt file using AES.

In .Net Rijndael encryption system (RijndaelManaged Class) is a part of cryptography (System.Security.Cryptography) . This class allows us to encrypt and decrypt file in .Net Environment.

Encryption Methodology

  • Create new file stream using FileStream Class.
  • Generate byte(UnicodeEncoding) of password(key) and initialization vector(IV)
  • Creates a symmetric Encryptor object with Key (Password) and initialization vector (IV). RijndaelManaged algorithm supports key lengths of 128, 192, or 256 bits.
  • Produced Crypto Stream using our original file with Encryptor object. Then write this crypto stream to our new file stream.

Encryption View

A simple form (encryptform) contain file and password fields are directly export data to controller method (EncryptFile

  1. <form action="@Url.Action("EncryptFile","Home")" method="post" enctype="multipart/form-data" id="encryptform">  
  2.    <input type="file" name="encryptfile" id="encryptfile" />  
  3.    <input type="password" name="password" minlength="5" id="password" />  
  4.    <button type="submit">Upload</button>  
  5. </form>  

Encryption Controller

Required namespaces

  1. using System.IO;  
  2. using System.Security.Cryptography;  
  3. using System.Text;  

The above three namespaces are required for encrypting and decrypting files. System.io use to create and read files, system.securtiy.cryptography for managing Rijndael streams for encrypting and decrypting files, finally system.Text for making key bytes from user password and initVector.

  1. public JsonResult EncryptFile(string password) {  
  2.     string InitVector = @ "qwertyui"//16byte 1chr = 2byte(unicode)  
  3.     string baseUrl = "D://";  
  4.     ReturnData result = new ReturnData();  
  5.     result.success = false;  
  6.     try {  
  7.         if (Request.Files.Count > 0) {  
  8.             HttpPostedFileBase file = Request.Files[0];  
  9.             string filename = Path.GetFileName(file.FileName);  
  10.             string outputFile = Path.Combine(baseUrl, "encry_" + filename);  
  11.             UnicodeEncoding UE = new UnicodeEncoding();  
  12.             byte[] key = UE.GetBytes(password);  
  13.             byte[] IV = UE.GetBytes(InitVector);  
  14.             FileStream fsCrypt = new FileStream(outputFile, FileMode.Create);  
  15.             RijndaelManaged RMCrypto = new RijndaelManaged();  
  16.             ICryptoTransform encryptor = RMCrypto.CreateEncryptor(key, IV);  
  17.             CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write);  
  18.             int data;  
  19.             while ((data = file.InputStream.ReadByte()) != -1) {  
  20.                 cs.WriteByte((byte) data);  
  21.             }  
  22.             file.InputStream.Close();  
  23.             cs.Close();  
  24.             fsCrypt.Close();  
  25.             result.success = true;  
  26.             result.url = "encry_" + filename;  
  27.             result.name = "encry_" + filename;  
  28.         }  
  29.     } catch (Exception e) {  
  30.         result.success = false;  
  31.         result.url = string.Empty;  
  32.         result.name = string.Empty;  
  33.         result.error = e.Message;  
  34.     }  
  35.     return Json(result, JsonRequestBehavior.AllowGet);  
  36. }  

Decryption Methodology

  1. Get encrypted file stream from HttpPostedFileBase file.
  2. Generate UnicodeEncoding byte of password(key) and initialization vector(IV)
  3. Creates a symmetric Decreptor object with the Key (Password) and initialization vector (IV).
  4. Produced Crypto Stream using our encrypted file with Decreptor object. Then write this decrypted files stream to new file. Finally the decrypted file is stored in Local Storage (D://)

Decryption View

  1. <form action="@Url.Action("DecryptFile", "Home")" method="post" enctype="multipart/form-data" id="decryptform">  
  2.    <input type="file" name="decryptfile" id="decryptfile" />  
  3.    <input type="password" name="password" id="password" />  
  4.    <button type="submit">Upload</button>  
  5. </form>  

Decryption Controller Method

  1. public JsonResult DecryptFile(string password) {  
  2.     string InitVector = @ "qwertyui";  
  3.     string baseUrl = "D://";  
  4.     ReturnData result = new ReturnData();  
  5.     try {  
  6.         if (Request.Files.Count > 0) {  
  7.             HttpPostedFileBase file = Request.Files[0];  
  8.             string filename = Path.GetFileName(file.FileName);  
  9.             string outputFile = Path.Combine(baseUrl, "decry_" + filename);  
  10.             UnicodeEncoding UE = new UnicodeEncoding();  
  11.             byte[] key = UE.GetBytes(password);  
  12.             byte[] IV = UE.GetBytes(InitVector);  
  13.             RijndaelManaged RMCrypto = new RijndaelManaged();  
  14.             ICryptoTransform decryptor = RMCrypto.CreateDecryptor(key, IV);  
  15.             CryptoStream cs = new CryptoStream(file.InputStream, decryptor, CryptoStreamMode.Read);  
  16.             FileStream fsOut = new FileStream(outputFile, FileMode.Create);  
  17.             int data;  
  18.             while ((data = cs.ReadByte()) != -1) {  
  19.                 fsOut.WriteByte((byte) data);  
  20.             }  
  21.             file.InputStream.Close();  
  22.             fsOut.Close();  
  23.             cs.Close();  
  24.             result.name = "decry_" + filename;  
  25.             result.url = "decry_" + filename;  
  26.             result.success = true;  
  27.         }  
  28.     } catch (Exception e) {}  
  29.     return new JsonResult {  
  30.         Data = result  
  31.     };  
  32. }  

Return Data Model Class

  1. public class ReturnData {  
  2.     public bool success {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string url {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string name {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string error {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
  • Name – Return final (encrypted/decrypted) file name.
  • Url – option to pass physical path of file result.
  • Success/error- status messages.

Summary

Rijndael algorithm is a common AES method for using worldwide to encrypt any kind of data. .NET Framework gives a simple RijndaelManaged cryptography class to manage encrypting and decrypting files safely.

Next Recommended Reading Encrypt and Decrypt a String in ASP.NET