Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have asp.net code to encrypt and decrypt files using Cryptography and Steganography to upload it to a server and return download it with the same manner. but asp.net code is run at server. how to make the encryption and decryption process executed at client side to avoid man in middle attack.

I don't have a problem with a code the code is work correctly but i want to make the encryption and decryption executed at client side.

What I have tried:

the following code is my asp.net code to encrypt at uploading:

I encrypt file using cryptography class
then hide the encrypted file with some header information into a cover image selected by the user using steganography class


protected void hidebtn_Click(object sender, EventArgs e)
  {
    if (fileBrowsebtn.HasFile && imageBrowsebtn.HasFile && encPass.Text != "")
    {
        //Get the Input File Name and Extension.
        string fileName = Path.GetFileNameWithoutExtension(fileBrowsebtn.PostedFile.FileName);
        string fileExtension = Path.GetExtension(fileBrowsebtn.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 + fileExtension + ".aes";

        //Save the Input File, Encrypt it and save the encrypted file in output path.
        fileBrowsebtn.SaveAs(input);
        FileInfo finfo = new FileInfo(input);
        long fileSize = finfo.Length;
        int fileNameSize = Path.GetFileNameWithoutExtension(output).Length;

        //Encrypt the File Using AES and generate encrypted byte array
        Cryptography encryptor = new Cryptography();
        byte[] fileContainer = encryptor.FileEncrypt(input, output, encPass.Text);

        //generate a new password for the next session using the current password  
        string Newpassword = encryptor.CreateRandomPassword(encPass.Text.Length);               
        byte[] Newpasswordbytes = System.Text.Encoding.UTF8.GetBytes(Newpassword);
        //Encrypt the file hash code and the new password using RSA
        byte[] RSAplain = Combine(encryptor.hashcode, Newpasswordbytes);                
         string pkpath = Server.MapPath("publickey.xml");
         byte[] RSAcipher = encryptor.RSAEncryptData(RSAplain, pkpath);
        byte[] header = new byte[3];

        //preparing the encode packet to embedded into the image
        int fileLength = fileContainer.Length;
        header[0] = (byte)((fileLength >> 16) & 0xff);
        header[1] = (byte)((fileLength >> 8) & 0xff);
        header[2] = (byte)(fileLength & 0xff);
        byte[] bytestobehidden = Combine(header, fileContainer);               
        bytestobehidden = Combine(bytestobehidden, RSAcipher);
        fileSize = bytestobehidden.Length;

        //prepare the cover image              
        string imgName = Path.GetFileName(imageBrowsebtn.PostedFile.FileName);
        string imgPath = Server.MapPath("~/Images/") + imgName;
        imageBrowsebtn.SaveAs(imgPath);                
        string stegimgpath = Server.MapPath("~/Images/") + fileName + "stego.bmp";
        Steganography Steg = new Steganography(imgPath);
        Bitmap stegImg = Steg.StegoLayer(fileSize, output, stegimgpath, bytestobehidden);                              
        string stgimgname = Path.GetFileName(stegimgpath);

        //uploading the stego-image and add the file to user DB
        DUser dataowner = new DUser();
        string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("StorageDB.mdb") + ";";
        dataowner.addFile((fileName + fileExtension), stgimgname, "false", constring);                

        //Delete the original (input) and the encrypted (output) file.
        File.Delete(input);
        File.Delete(output);
    }           
}


the following code is the extracting code before downloading :

First, i extract the data from the image

then decrypt it to get the original file

protected void extbtn_Click(object sender, EventArgs e)
  {
    if (fileList.SelectedIndex != -1 && decPass.Text != "")
    {              
        //Get the Input File Name and Extension
        string fileName = Path.GetFileNameWithoutExtension(fileList.SelectedItem.ToString());
        string fileExtension = Path.GetExtension(fileList.SelectedItem.ToString());
        string stgimname = Path.GetFileName(fileList.SelectedItem.Value);

        //Build the File Path for the original (input) and the decrypted (output) file
        string stgpath = Server.MapPath("~/Images/") + stgimname;


        //Extract the encode packet from the stegoimage
        Steganography stg = new Steganography(stgpath);
        string extFName = "";
        byte[] extBytes = stg.ExtractLayer(out extFName);
        int fileLength = (int)(extBytes[0] << 16) +
          (int)(extBytes[1] << 8) +
          (int)extBytes[2];

        //separate the encode packet element in separate arrays to decrypt
        byte[] filebytes = new byte[fileLength];
        byte[] RSACipher = new byte[extBytes.Length - fileLength - 3];
        System.Array.Copy(extBytes, 3, filebytes, 0, fileLength);
        System.Array.Copy(extBytes, fileLength + 3, RSACipher, 0, extBytes.Length - fileLength - 3);

        //decrypt the new password and hashcode using RSA
        Cryptography crypto = new Cryptography();
        string prpath = Server.MapPath("privatekey.xml");               
        byte[] hashplusnewpass = crypto.RSADecryptData(RSACipher,prpath);
        byte[] newpass = new byte[hashplusnewpass.Length - 32];
        byte[] oldhash = new byte[32];
        Array.Copy(hashplusnewpass, 0, oldhash, 0, 32);
        Array.Copy(hashplusnewpass, 32, newpass, 0, newpass.Length);

        //get the new generated password
        string newpasswrd = System.Text.Encoding.UTF8.GetString(newpass);
        Application["NewPass"] = newpasswrd;
         string newpassfile = Server.MapPath("~/Files/") + "newpassword.txt";
        //decrypt the File bytes using AES
        string input = Server.MapPath("~/Files/") + "ext" + extFName;
        string output = Server.MapPath("~/Files/") + "dec" + extFName;
        File.WriteAllBytes(input, filebytes);               
        crypto.FileDecrypt(input, output, decPass.Text);

        // get and compare the current and old hash values to validate the file
        byte[] outfilebytes = File.ReadAllBytes(output);
        byte[] curhashcode = SHA256.Create().ComputeHash(outfilebytes);
        if (!CompareByteArrays(oldhash, curhashcode))
            throw new CryptographicException("File Corrupted!");
        else
        {
           Infolbl.Visible = true;
           Infolbl.Text = "the data file is validated and The password for next session is generated";

        }   
           //Download the Decrypted File.
            Response.Clear();
            Response.ContentType = fileList.SelectedItem.GetType().ToString();
            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();                              
    }           
}
Posted
Updated 13-Mar-18 0:10am

1 solution

You can't encrypt the file at the client. Well, you probably could but it's worthless as you'd need to expose your "secrets" allowing anyone to decrypt your data. If you want to avoid man in the middle attacks then use https, that's what it's there for.
 
Share this answer
 
Comments
Member 12666574 13-Mar-18 6:20am    
can you tell me how to use https with this code, because i have little knowledge with it
F-ES Sitecore 13-Mar-18 6:22am    
Google how to obtain and apply an ssl certificate on your site, and from there you simply use https://yoursite/yourpage rather than http://yoursite/yourpage and the browser does the rest. The only code change you might need is to redirect people to the https version if they come to the http version.
Richard Deeming 13-Mar-18 10:33am    
You can get a free SSL certificate from Let's Encrypt[^]. There's even a simple command-line utility[^] to run on the server which will get you up and running in a few minutes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900