Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encrypt/decrypt arbitrary binary files using Javascript in the browser?

I need to let users load files from their system, encrypt them on-the-fly and upload to the server and do the opposite thing (download files from the server, decrypt on the fly and let the user save them locally). The exact crypto method is not very important although AES is preferred.

Links like Encryption / decryption of binary data in the browser just tell you "use CryptoJS" but I was unable to find any actually working samples. All samples I found focus on dealing with strings while in binary data you can easily find invalid Unicode sequences.

Is there any working sample I can test which can process files of any kind?

like image 561
Alex Avatar asked Nov 18 '16 15:11

Alex


People also ask

Can you Encrypt a JavaScript file?

No, it's not possible. If it runs on the client browser, it must be downloaded by the client browser.


1 Answers

Note: I won't explain how to decrypt the data, but that should be rather easy to figure out using the code for encryption and the documentation-links provided.

First of all, the user has to be able to select a file via an input element.

<input type="file" id="file-upload" onchange="processFile(event)">

You can then load the content of the file using the HTML5 FileReader API

function processFile(evt) {
    var file = evt.target.files[0],
        reader = new FileReader();

    reader.onload = function(e) {
        var data = e.target.result;

        // to be continued...
    }

    reader.readAsArrayBuffer(file);   
}

Encrypt the acquired data using the WebCrypto API.
If you don't want to randomly generate the key use crypto.subtle.deriveKey to create a key, for example, from a password that the user entered.

// [...]
var iv = crypto.getRandomValues(new Uint8Array(16)); // Generate a 16 byte long initialization vector

crypto.subtle.generateKey({ 'name': 'AES-CBC', 'length': 256 ]}, false, [ 'encrypt', 'decrypt' ])
    .then(key => crypto.subtle.encrypt({ 'name': 'AES-CBC', iv }, key, data))
    .then(encrypted => { /* ... */ });

Now you can send your encrypted data to the server (e.g. with AJAX). Obviously you will also have to somehow store the Initialization Vector to later successfully decrypt everything.


Here is a little example which alerts the length of the encrypted data.

Note: If it says Only secure origins are allowed, reload the page with https and try the sample again (This is a restriction of the WebCrypto API): HTTPS-Link

function processFile(evt) {
    var file = evt.target.files[0],
        reader = new FileReader();

    reader.onload = function(e) {
        var data = e.target.result,
            iv = crypto.getRandomValues(new Uint8Array(16));
      
        crypto.subtle.generateKey({ 'name': 'AES-CBC', 'length': 256 }, false, ['encrypt', 'decrypt'])
            .then(key => crypto.subtle.encrypt({ 'name': 'AES-CBC', iv }, key, data) )
            .then(encrypted => {
                console.log(encrypted);
                alert('The encrypted data is ' + encrypted.byteLength + ' bytes long'); // encrypted is an ArrayBuffer
            })
            .catch(console.error);
    }

    reader.readAsArrayBuffer(file);   
}
<input type="file" id="file-upload" onchange="processFile(event)">
like image 91
schroffl Avatar answered Oct 05 '22 21:10

schroffl