Encrypt and Decrypt File in ASP.NET Using C# and VB.NET

watch_later 1/27/2021

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.

Encrypt and Decrypt File in ASP.NET Using 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-familyArial;
            font-size10pt;
        }
 
        h1 {
            color#ff0097;
            text-shadow1px 1px 2px gray;
        }
 
        .button {
            background-color#ff0097;
            bordernone;
            colorwhite;
            padding20px 5.9%;
            margin-top15px;
            text-aligncenter;
            text-decorationnone;
            displayinline-block;
            font-size16px;
            border-radius5px;
            box-shadow0 2px 5px 0 rgba(0,0,0,0.16)0 2px 10px 0 rgba(0,0,0,0.12);
        }
 
        input[type="file"] {
            displaynone;
        }
 
        .custom-file-upload {
            cursorpointer;
            bordernone;
            color#223c88;
            padding20px 15%;
            text-aligncenter;
            text-decorationnone;
            displayinline-block;
            font-size16px;
            border-radius5px;
            box-shadow0 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 inputFilePathstring outputfilePath)
{
    string EncryptionKey = "CODINGVILA";
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKeynew 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(outputfilePathFileMode.Create))
        {
            using (CryptoStream cs = new CryptoStream(fsOutputencryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                using (FileStream fsInput = new FileStream(inputFilePathFileMode.Open))
                {
                    int data;
                    while ((data = fsInput.ReadByte()) != -1)
                    {
                        cs.WriteByte((byte)data);
                    }
                }
            }
        }
    }
}
protected void EncryptFile_Click(object senderEventArgs 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(inputoutput);
 
    //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 TByVal value As TAs T
        source = value
        Return value
    End Function
Private Sub Encrypt(inputFilePath As StringoutputfilePath As String)
        Dim EncryptionKey As String = "CODINGVILA"
        Using encryptor As Aes = Aes.Create()
            Dim pdb As New Rfc2898DeriveBytes(EncryptionKeyNew 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(outputfilePathFileMode.Create)
                Using cs As New CryptoStream(fsencryptor.CreateEncryptor(), CryptoStreamMode.Write)
                    Using fsInput As New FileStream(inputFilePathFileMode.Open)
                        Dim data As Integer
                        While (Assign(datafsInput.ReadByte())) <> -1
                            cs.WriteByte(CByte(data))
                        End While
                    End Using
                End Using
            End Using
        End Using
    End Sub
Protected Sub EncryptFile_Click(sender As Objecte 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(inputoutput)
 
        '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 inputFilePathstring outputfilePath)
{
    string EncryptionKey = "CODINGVILA";
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKeynew 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(inputFilePathFileMode.Open))
        {
            using (CryptoStream cs = new CryptoStream(fsInputencryptor.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using (FileStream fsOutput = new FileStream(outputfilePathFileMode.Create))
                {
                    int data;
                    while ((data = cs.ReadByte()) != -1)
                    {
                        fsOutput.WriteByte((byte)data);
                    }
                }
            }
        }
    }
}
protected void DecryptFile_Click(object senderEventArgs 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(inputoutput);
 
    //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 TByVal value As TAs T
        source = value
        Return value
    End Function
Private Sub Decrypt(inputFilePath As StringoutputfilePath As String)
        Dim EncryptionKey As String = "CODINGVILA"
        Using encryptor As Aes = Aes.Create()
            Dim pdb As New Rfc2898DeriveBytes(EncryptionKeyNew 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(inputFilePathFileMode.Open)
                Using cs As New CryptoStream(fsencryptor.CreateDecryptor(), CryptoStreamMode.Read)
                    Using fsOutput As New FileStream(outputfilePathFileMode.Create)
                        Dim data As Integer
                        While (Assign(datacs.ReadByte())) <> -1
                            fsOutput.WriteByte(CByte(data))
                        End While
                    End Using
                End Using
            End Using
        End Using
    End Sub
Protected Sub DecryptFile_Click(sender As Objecte 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(inputoutput)
 
        '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


Encryption and Description

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.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon