Reputation: 2609
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?
Upvotes: 15
Views: 29669
Reputation: 1594
You can convert a file into blob using:
new Blob([document.querySelector('input').files[0]])
Here's the code to encrypt & decrypt a blob
async function encryptblob(blob) {
let iv = crypto.getRandomValues(new Uint8Array(12));
let algorithm = {
name: "AES-GCM",
iv: iv
}
let key = await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
let data = await blob.arrayBuffer();
const result = await crypto.subtle.encrypt(algorithm, key, data);
let exportedkey = await crypto.subtle.exportKey("jwk", key)
return [new Blob([result]), iv.toString(), exportedkey]
}
async function decryptblob(encblob, ivdata, exportedkey) {
let key = await crypto.subtle.importKey(
"jwk",
exportedkey,
{ name: "AES-GCM" },
true,
["encrypt", "decrypt"]
);
let iv = new Uint8Array(ivdata.split(','))
let algorithm = {
name: "AES-GCM",
iv: iv
}
let data = await encblob.arrayBuffer();
let decryptedData = await crypto.subtle.decrypt(algorithm, key, data);
return new Blob([decryptedData])
}
Upvotes: 4
Reputation: 12037
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.
Upvotes: 8
Reputation: 589
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)">
Upvotes: 15