Skip to content

Instantly share code, notes, and snippets.

@dpogorzelski
Last active December 25, 2015 14:29
Show Gist options
  • Save dpogorzelski/6991027 to your computer and use it in GitHub Desktop.
Save dpogorzelski/6991027 to your computer and use it in GitHub Desktop.
Client-side File Encryption: Frontend
//This is the service which is injected inside the controller and encrypts each
//file in the array generated by the directive
services.service('Crypt', [
function() {
this.bury = function(file, key, callback) {
// we need a new FileReader instance to read the file's content
var reader = new FileReader();
//we read the content as array buffer so we can handle binary data
//too
reader.readAsArrayBuffer(file);
reader.onloadend = function() {
//we interpret the arraybuffer's content as Uint8Array
//so we can encode each byte as utf8 char
//Note: with small files you could pass the 'content' array
//directly to String.fromCharCode but with bigger files you'll
//get "Maximum call stack size exceeded" so need to handle each
var content = new Uint8Array(this.result);
var utf8 = "";
for (var i = 0, len = content.length; i < len; i++) {
utf8 += String.fromCharCode(content[i]);
}
//at this point we encode the utf8 string to base64. you might
//wonder why: I found problems after binary file decryption
//if encryption was performed on utf8 string directly
var b64 = btoa(utf8);
//we finally encrypt it
var encrypted = GibberishAES.enc(b64, key);
var blob = new Blob([encrypted], {
type: 'application/octet-stream'
});
//and return a new blob to the controller
callback({
blob: blob,
name: file.name
});
}
}
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment