An Easy Way To Encode And Decode File In ASP.NET

Introduction

In this article, I’ll explain a way to encode and decode a file in ASP.NET using C# and VB.NET with an example.

Recently, I required searching out an easy way to encode and decode a file of any kind (I actually required to encode images and text files) and any size. I found many examples online, several of them did not work, or threw errors on sure file varieties.

Encryption - The process of changing data or information into a code, particularly to stop unauthorized access.

Decryption - The method of taking encoded or encrypted text or alternative information and changing it back to text that you simply or the pc will browse and perceive. This term may be used to describe a way of un-encrypting the information manually or with un-encrypting the information using the right codes or keys.

The files are uploaded for encoding and decoding of files. The AES symmetric algorithm is used for encoding and decoding of the files. The encrypted and decrypted files may be saved within folders on disk or may be downloaded to shopper user.

So, in this article, I’ll explain a way to encode and decode the file in ASP.NET with an example.

HTML Code Markup

The HyperText Markup Language consists of File Upload control and 2 buttons.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7.     <style type="text/css">  
  8.         body  
  9.         {  
  10.             font-family: Arial;  
  11.             font-size: 10pt;  
  12.         }  
  13.         .button {  
  14.     background-color: #ff6a00; /* Green */  
  15.     border: none;  
  16.     color: white;  
  17.     padding: 10px 22px;  
  18.     text-align: center;  
  19.     text-decoration: none;  
  20.     display: inline-block;  
  21.     font-size: 16px;  
  22. }  
  23.   
  24.     </style>  
  25. </head>  
  26. <body>  
  27.     <form id="form1" runat="server">  
  28.     <asp:FileUpload CssClass="button"  ID="FileUpload1" runat="server" />  
  29.     <hr />  
  30.     <asp:Button ID="btnEncrypt" CssClass="button" Text="Encrypt File" runat="server" OnClick="EncryptFile" />  
  31.        
  32.     <asp:Button ID="btnDecrypt" CssClass="button" Text="Decrypt File" runat="server" OnClick="DecryptFile" />  
  33.     </form>  
  34. </body>  
  35. </html>  

Namespaces

You will have to be compelled to import the subsequent namespaces.

C#

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

VB.NET

  1. Imports System.IO  
  2. Imports System.Security.Cryptography  

AES algorithm encoding and decoding functions

Below are the functions for encoding and decoding which are used for Encrypting or Decrypting Files.

File encoding

The following Button-click event handler encrypts the uploaded file. Name, Content type, and therefore the File Bytes of the uploaded file, are fetched and therefore the file is saved in a folder on disk.

The encrypted file is then sent for transfer by the shopper user. Once transferred,  each of the files is deleted.

C#

  1. protected void EncryptFile(object sender, EventArgs e)  
  2. {  
  3.     //Get the Input File Name and Extension.  
  4.     string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);  
  5.     string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);  
  6.   
  7.     //Build the File Path for the original (input) and the encrypted (output) file.  
  8.     string input = Server.MapPath("~/Files/") + fileName + fileExtension;  
  9.     string output = Server.MapPath("~/Files/") + fileName + "_enc" + fileExtension;  
  10.   
  11.     //Save the Input File, Encrypt it and save the encrypted file in output path.  
  12.     FileUpload1.SaveAs(input);  
  13.     this.Encrypt(input, output);  
  14.   
  15.     //Download the Encrypted File.  
  16.     Response.ContentType = FileUpload1.PostedFile.ContentType;  
  17.     Response.Clear();  
  18.     Response.AppendHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(output));  
  19.     Response.WriteFile(output);  
  20.     Response.Flush();  
  21.   
  22.     //Delete the original (input) and the encrypted (output) file.  
  23.     File.Delete(input);  
  24.     File.Delete(output);  
  25.   
  26.     Response.End();  
  27. }  
  1. private void Encrypt(string inputFilePath, string outputfilePath)  
  2. {  
  3.     string EncryptionKey = "MAKV2SPBNI99212";  
  4.     using (Aes encryptor = Aes.Create())  
  5.     {  
  6.         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });  
  7.         encryptor.Key = pdb.GetBytes(32);  
  8.         encryptor.IV = pdb.GetBytes(16);  
  9.         using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))  
  10.         {  
  11.             using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))  
  12.             {  
  13.                 using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))  
  14.                 {  
  15.                     int data;  
  16.                     while ((data = fsInput.ReadByte()) != -1)  
  17.                     {  
  18.                         cs.WriteByte((byte)data);  
  19.                     }  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  

VB.NET

  1. Protected Sub EncryptFile(sender As Object, e As EventArgs)  
  2.         'Get the Input File Name and Extension.  
  3.         Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName)  
  4.         Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)  
  5.   
  6.         'Build the File Path for the original (input) and the encrypted (output) file.  
  7.         Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension  
  8.         Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_enc") & fileExtension  
  9.   
  10.         'Save the Input File, Encrypt it and save the encrypted file in output path.  
  11.         FileUpload1.SaveAs(input)  
  12.         Me.Encrypt(input, output)  
  13.   
  14.         'Download the Encrypted File.  
  15.         Response.ContentType = FileUpload1.PostedFile.ContentType  
  16.         Response.Clear()  
  17.         Response.AppendHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(output))  
  18.         Response.WriteFile(output)  
  19.         Response.Flush()  
  20.   
  21.         'Delete the original (input) and the encrypted (output) file.  
  22.         File.Delete(input)  
  23.         File.Delete(output)  
  24.   
  25.         Response.End()  
  26.     End Sub

  1. Protected Sub DecryptFile(sender As Object, e As EventArgs)  
  2.         'Get the Input File Name and Extension  
  3.         Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName)  
  4.         Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)  
  5.   
  6.         'Build the File Path for the original (input) and the decrypted (output) file  
  7.         Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension  
  8.         Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_dec") & fileExtension  
  9.   
  10.         'Save the Input File, Decrypt it and save the decrypted file in output path.  
  11.         FileUpload1.SaveAs(input)  
  12.         Me.Decrypt(input, output)  
  13.   
  14.         'Download the Decrypted File.  
  15.         Response.Clear()  
  16.         Response.ContentType = FileUpload1.PostedFile.ContentType  
  17.         Response.AppendHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(output))  
  18.         Response.WriteFile(output)  
  19.         Response.Flush()  
  20.   
  21.         'Delete the original (input) and the decrypted (output) file.  
  22.         File.Delete(input)  
  23.         File.Delete(output)  
  24.   
  25.         Response.End()  
  26.     End Sub  

For VB.NET, I actually have created use of a utility technique named Assign for distribution variable values and additionally returning a constant. In C#, it is done simply, however, to try the same in VB.NET we'd like a utility technique.

File decoding

Similar to the encoding method, the subsequent Button click event handler encrypts the uploaded file. Name, Content type, and therefore the File Bytes of the uploaded file, are fetched and therefore the file is saving in a folder on disk.

The decrypted file is then sent for transfer by the shopper user. Once transferred, all the files are deleted.

C#

  1. protected void DecryptFile(object sender, EventArgs e)  
  2. {  
  3.     //Get the Input File Name and Extension  
  4.     string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);  
  5.     string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);  
  6.   
  7.     //Build the File Path for the original (input) and the decrypted (output) file  
  8.     string input = Server.MapPath("~/Files/") + fileName + fileExtension;  
  9.     string output = Server.MapPath("~/Files/") + fileName + "_dec" + fileExtension;  
  10.   
  11.     //Save the Input File, Decrypt it and save the decrypted file in output path.  
  12.     FileUpload1.SaveAs(input);  
  13.     this.Decrypt(input, output);  
  14.   
  15.     //Download the Decrypted File.  
  16.     Response.Clear();  
  17.     Response.ContentType = FileUpload1.PostedFile.ContentType;  
  18.     Response.AppendHeader("Content-Disposition""attachment; filename=" + Path.GetFileName(output));  
  19.     Response.WriteFile(output);  
  20.     Response.Flush();  
  21.   
  22.     //Delete the original (input) and the decrypted (output) file.  
  23.     File.Delete(input);  
  24.     File.Delete(output);  
  25.   
  26.     Response.End();  
  27. }

  1. private void Decrypt(string inputFilePath, string outputfilePath)  
  2. {  
  3.     string EncryptionKey = "MAKV2SPBNI99212";  
  4.     using (Aes encryptor = Aes.Create())  
  5.     {  
  6.         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });  
  7.         encryptor.Key = pdb.GetBytes(32);  
  8.         encryptor.IV = pdb.GetBytes(16);  
  9.         using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))  
  10.         {  
  11.             using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))  
  12.             {  
  13.                 using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))  
  14.                 {  
  15.                     int data;  
  16.                     while ((data = cs.ReadByte()) != -1)  
  17.                     {  
  18.                         fsOutput.WriteByte((byte)data);  
  19.                     }  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  

VB.NET

  1. Private Sub Encrypt(inputFilePath As String, outputfilePath As String)  
  2.      Dim EncryptionKey As String = "MAKV2SPBNI99212"  
  3.      Using encryptor As Aes = Aes.Create()  
  4.          Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _  
  5.           &H65, &H64, &H76, &H65, &H64, &H65, _  
  6.           &H76})  
  7.          encryptor.Key = pdb.GetBytes(32)  
  8.          encryptor.IV = pdb.GetBytes(16)  
  9.          Using fs As New FileStream(outputfilePath, FileMode.Create)  
  10.              Using cs As New CryptoStream(fs, encryptor.CreateEncryptor(), CryptoStreamMode.Write)  
  11.                  Using fsInput As New FileStream(inputFilePath, FileMode.Open)  
  12.                      Dim data As Integer  
  13.                      While (Assign(data, fsInput.ReadByte())) <> -1  
  14.                          cs.WriteByte(CByte(data))  
  15.                      End While  
  16.                  End Using  
  17.              End Using  
  18.          End Using  
  19.      End Using  
  20.  End Sub

  1.  Private Sub Decrypt(inputFilePath As String, outputfilePath As String)  
  2.      Dim EncryptionKey As String = "MAKV2SPBNI99212"  
  3.      Using encryptor As Aes = Aes.Create()  
  4.          Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _  
  5.           &H65, &H64, &H76, &H65, &H64, &H65, _  
  6.           &H76})  
  7.          encryptor.Key = pdb.GetBytes(32)  
  8.          encryptor.IV = pdb.GetBytes(16)  
  9.          Using fs As New FileStream(inputFilePath, FileMode.Open)  
  10.              Using cs As New CryptoStream(fs, encryptor.CreateDecryptor(), CryptoStreamMode.Read)  
  11.                  Using fsOutput As New FileStream(outputfilePath, FileMode.Create)  
  12.                      Dim data As Integer  
  13.                      While (Assign(data, cs.ReadByte())) <> -1  
  14.                          fsOutput.WriteByte(CByte(data))  
  15.                      End While  
  16.                  End Using  
  17.              End Using  
  18.          End Using  
  19.      End Using  
  20.  End Sub  

Output Screen

  1. User Interface.

    Output

  2. Encrypted File.

    Output

  3. Decrypted File.

    Output


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