How to encrypt binary using HTML5 API files and upload to server

I need to encrypt and upload a file to Apache / PHP server using HTML5 FileReader API and CryptoJS

I have done the following successfully

  • Reading a file using the FileReader API
  • Convert file to base64 using function readAsDataURL()
  • Encrypt it with

    CryptoJS.AES.encrypt (e.target.result, password);

But I was not able to send it to the server as an object File, because I already converted it to a text object, and I can not convert it back to a file. Below is my javascript file and server side snippet.


app.js
 var reader = new FileReader();

 // Read file callback!
 reader.onload = function (e) {

     // Use the CryptoJS library and the AES cypher to encrypt the 
     // contents of the file, held in e.target.result, with the password

     var encrypted = CryptoJS.AES.encrypt(e.target.result, password);


     //SEND FORM DATA
     var data = new FormData($("#fileinfo")[0]);

    /*The following line doesn't work because I'm not adding a File object, 
    * I'm adding file already converted to Base64 format
    */
     data.append('file-0','data:application/octet-stream,' + encrypted);

     $.ajax({
         url: 'upload.php',
         data: data,
         cache: false,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function (data) {
             //alert(data);
         }
     });

 };

<h / "> upload.php

<?php
var_dump($_FILES); //prints empty array
var_dump($_POST); //prints file as string 
?>
+4
1

w3 , -

var reader = new FileReader();

// Read file callback!
reader.onload = function (e) {

var encrypted = CryptoJS.AES.encrypt(e.target.result, password);

var data = new FormData($("#fileinfo")[0]);

var encryptedFile = new File([encrypted], file.name + '.encrypted', {type: "text/plain", lastModified: new Date()});

data.append('file[0]', encryptedFile);

$.ajax({
     url: 'upload.php',
     data: data,
     cache: false,
     contentType: false,
     processData: false,
     type: 'POST',
     success: function (data) {
         //alert(data);
     }
 });

};

reader.readAsDataURL(file);
+4

All Articles