In this article I will explain how to encrypt and decrypt file such as Word (DOC, DOCX), Excel (XLS, XLSX), PDF, Text (TXT) documents or JPG, PNG or GIF Images using C# and VB.Net in ASP.Net website.
The file will be uploaded for Encryption and Decryption of Files. For Encryption and Decryption of files, the AES Symmetric key (Same key) algorithm is used. The encrypted and decrypted files can be saved inside folders on disk or can be downloaded to client user.
 
HTML Markup
The HTML markup consists of FileUpload control and two Buttons.
<asp:FileUpload ID="FileUpload1" runat="server" />
<hr />
<asp:Button ID = "btnEncrypt" Text="Encrypt File" runat="server" OnClick = "EncryptFile" />
<asp:Button ID = "btnDecrypt" Text="Decrypt File" runat="server" OnClick = "DecryptFile" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Security.Cryptography;
 
VB.Net
Imports System.IO
Imports System.Security.Cryptography
 
 
AES Algorithm Encryption and Decryption functions
Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting Files.
Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net
 
File Encryption
The following Button click event handler encrypts the uploaded file. Name, Content Type and the File Bytes of the uploaded file are fetched and the file is save on folder on disk.
Once the file is saved in the same location its encrypted counterpart is saved with the postfix “_enc”.
The encrypted file is then sent for download by the client user. After download both the files are deleted.
C#
protected void EncryptFile(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 + "_enc" + 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();
}
 
private void Encrypt(string inputFilePath, string outputfilePath)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    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);
                    }
                }
            }
        }
    }
}
 
VB.Net
Protected Sub EncryptFile(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) + "_enc") & 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
 
Protected Sub DecryptFile(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) + "_dec") & 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
 
Private Shared Function Assign(Of T)(ByRef source As T, ByVal value As T) As T
    source = value
    Return value
End Function
 
For VB.Net I have made use of a utility method named Assign for assigning variable values and also returning the same. In C# it can be done easily but to do same in VB.Net we need a utility method.
 
 
File Decryption
Similar to Encryption process, the following Button click event handler encrypts the uploaded file. Name, Content Type and the File Bytes of the uploaded file are fetched and the file is save on folder on disk.
Once the file is saved in the same location its decrypted counterpart is saved with the postfix “_dec”.
The decrypted file is then sent for download by the client user. After download both the files are deleted.
C#
protected void DecryptFile(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 + "_dec" + 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();
}
 
private void Decrypt(string inputFilePath, string outputfilePath)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    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);
                    }
                }
            }
        }
    }
}
 
VB.Net
Private Sub Encrypt(inputFilePath As String, outputfilePath As String)
    Dim EncryptionKey As String = "MAKV2SPBNI99212"
    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
 
Private Sub Decrypt(inputFilePath As String, outputfilePath As String)
    Dim EncryptionKey As String = "MAKV2SPBNI99212"
    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
 
Encrypt and Decrypt Word, Excel, PDF, Text or Image Files using C# and VB.Net in ASP.Net
 
Downloads