Skip to content

Instantly share code, notes, and snippets.

@thoraxe
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoraxe/4d4fa78bdc0b4605eed9 to your computer and use it in GitHub Desktop.
Save thoraxe/4d4fa78bdc0b4605eed9 to your computer and use it in GitHub Desktop.
// get the encrypted string which is base64 encoded
var encrypted_string = $("#file-contents").val();
// base64 decode it
var wordarray = CryptoJS.enc.Base64.parse(encrypted_string);
// convert back to AES object
var decryptstring = CryptoJS.enc.Utf16.stringify(wordarray);
// fetch the password - this should be typed into a form.
var decryptpassword = "#{params[:password]}";
// decrypt the contents
var decrypted = CryptoJS.AES.decrypt(decryptstring, decryptpassword);
// this is our blob guts
var content = decrypted.toString(CryptoJS.enc.Utf8);
$(document).ready(
function() {
$("#encrypt-button").on("click", readSingleFile);
function readSingleFile(event) {
var file = $('#file')[0].files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(file) {
var contents = event.target.result;
// grab the password the user supplied
var key = $('#password').val();
var wordthing = CryptoJS.lib.WordArray.create(reader.result);
// encrypt using the supplied password
var encrypted = CryptoJS.AES.encrypt(wordthing, key);
// create a wordarray from the encrypted string
var wordarray = CryptoJS.enc.Utf16.parse(encrypted.toString());
// base64 that
var base64 = CryptoJS.enc.Base64.stringify(wordarray);
// update the hidden file contents field
$("#file_contents").val(base64);
// submitting the form PUTs the data
$("#file_form").submit();
};
reader.onerror = function(event) {
console.error("File could not be read! Code "
+ event.target.error.code);
};
reader.readAsArrayBuffer(file);
}
}
});
AFUAMgBGAHMAZABHAFYAawBYADEAOQBIAGgAeQArAFoASABzAEUASwB6AGEAcABhAHEAawBSAE0AbgBsADcAYgAxAGQAbQB
SAFcAZQBHAHgARABFAHgAKwBJAEQAdgA2AHMAUwB2AGUATAA0AHgAbQBkAGUATQBzAHgAaAB2AEQAbgByAHkASgBGAFYAYQBaADIAYwB1AHcANQBDAFoARQBwADYANQBDADEAMAA4AGUAOQAzAGQAcQBoACsAbQBlADcAQQBEACsALwByAEkAZgBDAGcAbwA9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment