Introduction
This article gives an explanation about how to encrypt and decrypt the file in ASP.NET using C# and VB.NET with a simple example. Here, I'll also explain what is encryption and description process in ASP.NET using AES symmetric algorithm.
Today, I got a requirement to encrypt and decrypt the file to prevent unauthorized activity while transferring a file from client to server and server to the client. To archive requirement, I have used AES symmetric algorithm to encrypt and decrypt the file in ASP.NET. So In this article, I am going to explain what is AES Encryption in C# and how to encrypt and decrypt the file using AES Encryption in C# and VB.NET.
In my previous article, I explained Calculate The SUM of the DataTable Column in ASP.NET and Datatable to CSV using C# and Insert data in GridView without using a database in ASP.NET and How to Get Selected Row Cell Value From The GridView in ASP.Net Web Forms and Upload and Save File in Database as VARBINARY Data in ASP.NET using C# and VB.NET as well as Export All The Excel Sheets to DataSet in C# and VB.NET that you might like to read.
Requirement
1) What is encryption and description?
2) What is the AES Encryption algorithm?
3) How to encrypt and decrypt the file using AES Encryption in ASP.NET.
Implementation
So, let's start the implementation of the given requirement.
What is encryption?
The process of converting the data or information (Plaintext) into meaningless or unrecognizable form (Ciphertext).
What is description?
The process of converting the meaningless or unrecognizable form (Ciphertext) into a readable or recognizable form (Plaintext) that can understand by a human or a computer.
What is AES Encryption Algorithm?
It is a symmetric encryption algorithm and it allows encryption and decryption of data or information using the same key.
So, let's take an example and understand how to encrypt and decrypt the file using Advanced Encryption Standard (AES) encryption.
Let's Create a simple ASP.NET webforms application and write the following code in the .aspx file.
HTML Code Markup
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } h1 { color: #ff0097; text-shadow: 1px 1px 2px gray; } .button { background-color: #ff0097; border: none; color: white; padding: 20px 5.9%; margin-top: 15px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; border-radius: 5px; box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16), 0 2px 10px 0 rgba(0,0,0,0.12); } input[type="file"] { display: none; } .custom-file-upload { cursor: pointer; border: none; color: #223c88; padding: 20px 15%; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; border-radius: 5px; box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16), 0 2px 10px 0 rgba(0,0,0,0.12); } </style> </head> <body> <form id="form1" runat="server"> <h1>Encryption and Description | ASP.NET</h1> <label for="FileUpload1" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i> File </label> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /> <asp:Button ID="btnEncrypt" CssClass="button" Text="Encrypt File" runat="server" OnClick="EncryptFile_Click" /> <asp:Button ID="btnDecrypt" CssClass="button" Text="Decrypt File" runat="server" OnClick="DecryptFile_Click" /> </form> </body> </html>
Explanation
As you can see in the above HTML code markup we have used 2 server-side controls first is the FileUpload control for browse the file and the second is a Button for encrypting and decrypt the selected file. Here, we have used the CssClass property for server-side control and CSS property for normal HTML control to apply custom CSS style on the control for a better user interface. We have also generated an OnClick event for buttons, to encrypt and decrypt the selected file based on the click event of the button.
Now, we have to write the code into code-behind, and first, we have to import the required namespace to use the AES encryption algorithm.
Namespace C#
using System.IO; using System.Security.Cryptography;
Namespace VB.NET
Imports System.IO Imports System.Security.Cryptography
Now, We will write a method to encrypt and decrypt the file in code-behind.
Encrypt C#
private void Encrypt(string inputFilePath, string outputfilePath) { string EncryptionKey = "CODINGVILA"; using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create)) { using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open)) { int data; while ((data = fsInput.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } }
protected void EncryptFile_Click(object sender, EventArgs e) { //Get the Input File Name and Extension. string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName); //Build the File Path for the original (input) and the encrypted (output) file. string input = Server.MapPath("~/Files/") + fileName + fileExtension; string output = Server.MapPath("~/Files/") + fileName + "_Encrypted" + fileExtension; //Save the Input File, Encrypt it and save the encrypted file in output path. FileUpload1.SaveAs(input); this.Encrypt(input, output); //Download the Encrypted File. Response.ContentType = FileUpload1.PostedFile.ContentType; Response.Clear(); Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)); Response.WriteFile(output); Response.Flush(); //Delete the original (input) and the encrypted (output) file. File.Delete(input); File.Delete(output); Response.End(); }
Encrypt VB.NET
Private Shared Function Assign(Of T)(ByRef source As T, ByVal value As T) As T source = value Return value End Function
Private Sub Encrypt(inputFilePath As String, outputfilePath As String) Dim EncryptionKey As String = "CODINGVILA" Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using fs As New FileStream(outputfilePath, FileMode.Create) Using cs As New CryptoStream(fs, encryptor.CreateEncryptor(), CryptoStreamMode.Write) Using fsInput As New FileStream(inputFilePath, FileMode.Open) Dim data As Integer While (Assign(data, fsInput.ReadByte())) <> -1 cs.WriteByte(CByte(data)) End While End Using End Using End Using End Using End Sub
Protected Sub EncryptFile_Click(sender As Object, e As EventArgs) 'Get the Input File Name and Extension. Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName) 'Build the File Path for the original (input) and the encrypted (output) file. Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_Encrypted") & fileExtension 'Save the Input File, Encrypt it and save the encrypted file in output path. FileUpload1.SaveAs(input) Me.Encrypt(input, output) 'Download the Encrypted File. Response.ContentType = FileUpload1.PostedFile.ContentType Response.Clear() Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)) Response.WriteFile(output) Response.Flush() 'Delete the original (input) and the encrypted (output) file. File.Delete(input) File.Delete(output) Response.End() End Sub
Explanation
As you can see in the code above we have generated the Click event of button EncryptFile. In this event we have written the code to get the input file name and file extension, then we created a file path for the original (input) file and the encrypted (output) file. Then, we have saved the input file, encrypt it and save the encrypted file in the output path and finally download the encrypted file and delete the original (input) and the encrypted (output) file from the server.
Let's write the code to decrypt the file in code-behind.
Decrypt C#
private void Decrypt(string inputFilePath, string outputfilePath) { string EncryptionKey = "CODINGVILA"; using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open)) { using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read)) { using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create)) { int data; while ((data = cs.ReadByte()) != -1) { fsOutput.WriteByte((byte)data); } } } } } }
protected void DecryptFile_Click(object sender, EventArgs e) { //Get the Input File Name and Extension string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName); //Build the File Path for the original (input) and the decrypted (output) file string input = Server.MapPath("~/Files/") + fileName + fileExtension; string output = Server.MapPath("~/Files/") + fileName + "_Decrypted" + fileExtension; //Save the Input File, Decrypt it and save the decrypted file in output path. FileUpload1.SaveAs(input); this.Decrypt(input, output); //Download the Decrypted File. Response.Clear(); Response.ContentType = FileUpload1.PostedFile.ContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)); Response.WriteFile(output); Response.Flush(); //Delete the original (input) and the decrypted (output) file. File.Delete(input); File.Delete(output); Response.End(); }
Decrypt VB.NET
Private Shared Function Assign(Of T)(ByRef source As T, ByVal value As T) As T source = value Return value End Function
Private Sub Decrypt(inputFilePath As String, outputfilePath As String) Dim EncryptionKey As String = "CODINGVILA" Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using fs As New FileStream(inputFilePath, FileMode.Open) Using cs As New CryptoStream(fs, encryptor.CreateDecryptor(), CryptoStreamMode.Read) Using fsOutput As New FileStream(outputfilePath, FileMode.Create) Dim data As Integer While (Assign(data, cs.ReadByte())) <> -1 fsOutput.WriteByte(CByte(data)) End While End Using End Using End Using End Using End Sub
Protected Sub DecryptFile_Click(sender As Object, e As EventArgs) 'Get the Input File Name and Extension Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName) 'Build the File Path for the original (input) and the decrypted (output) file Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_Decrypted") & fileExtension 'Save the Input File, Decrypt it and save the decrypted file in output path. FileUpload1.SaveAs(input) Me.Decrypt(input, output) 'Download the Decrypted File. Response.Clear() Response.ContentType = FileUpload1.PostedFile.ContentType Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)) Response.WriteFile(output) Response.Flush() 'Delete the original (input) and the decrypted (output) file. File.Delete(input) File.Delete(output) Response.End() End Sub
Explanation
As you can see in the code above we have generated the Click event of button DecryptFile. In this event we have written the code to get the input file name and file extension, then we created a file path for the encrypted (input) file and the decrypted (output) file. Then, we have saved the input file, decrypt it and save the decrypted file in the output path and finally download the decrypted file and delete the encrypted (input) and the decrypted (output) file from the server.
Output Screen
Summary
In this article, we learned an easy way to encode and decode the file In ASP.NET using C# and VB.NET as well as also get the basic knowledge about the AES Encryption algorithm.