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

后端 未结 2 1761
傲寒
傲寒 2021-02-09 17:55

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

相关标签:
2条回答
  • 2021-02-09 18:28

    See https://github.com/meixler/web-browser-based-file-encryption-decryption for an example showing encryption/decryption of arbitrary binary files using Javascript in the web browser, based on the Web Crypto API.

    0 讨论(0)
  • 2021-02-09 18:50

    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)">

    0 讨论(0)
提交回复
热议问题