Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Encrypted File Upload

Is there a way to use javascript or ajax to encrypt file uploads, if so can you give me an example or link to working example?

like image 453
AgentPigman Avatar asked Sep 01 '15 22:09

AgentPigman


1 Answers

The answer is Yes, there is a way to use javascript or ajax to encrypt file uploads. You can use standard Web APIs that have built-in native support in browsers: Use the standard File API and WebCrypto API to get the file from your filesystem and actually encrypt it—along with the Indexed Database API (indexedDB) (if you want) to store the encrypted file on the client side in the browser. A good simple example with working code is at Upload a file, encrypt it, calculate the hash and store the results using indexedDB.

Short summary of how to do it

The first step is just the normal step of creating an input type=file element in your HTML, and binding a function to it for getting the file from your filesystem and doing something with it; e.g., use onsubmit="my_file_handler".

After that, inside your my_file_handler (or whatever name) function:

  1. Use .files[…] from that to get the input file(s).
  2. Define a function that takes a cryptographic key; within that function:

    • create a new FileReader object and use, e.g., .readAsArrayBuffer(…) to load the file
    • use crypto.subtle to create a new SubtleCrypto object
    • use .digest(…) with that SubtleCrypto object and then crypto.subtle.encrypt(…) to actually encrypt the file with that key
    • use indexedDB.open(…) and friends to open a connection to a DB and to put the encrypted file into it.
  3. Use .importKey(…) to get the key and call your function in step #2 on it to process the input file with it and store it using indexedDB.
like image 126
sideshowbarker Avatar answered Oct 19 '22 15:10

sideshowbarker