SJCL encryption results wrong file size

797 views Asked by At

I have successfully implemented Rob Napier's AES encryption method for iOS in one of my apps. I would now like to be able to encrypt and decrypt files from that app with my JavaScript implementation. I am using FileReader to get a local from from the user and loading it with

reader.readAsArrayBuffer(file);

When this is done the file gets encrypted using the Stanford JavaScript Crypto Library and finally the encrypted file can be downloaded:

reader.onloadend = function(e) {

    var content = new Uint8Array(e.target.result);
    var utf8 = "";
    for (var i = 0, len = content.length; i < len; i++) {
         utf8 += String.fromCharCode(content[i]);
    }
    var b64 = btoa(utf8);

    //we finally encrypt it 
    var encrypted = sjcl.encrypt(password, b64,{ks:256});
    var json = JSON.parse(encrypted);
    var ciphertext = json.ct;

    a.attr('href', 'data:application/octet-stream,' + ciphertext);
    a.attr('download', file.name + '.encrypted');

    step(4);

    };

reader.readAsArrayBuffer(file);

The problem is that the encrypted file is much larger than the original. This is not the case in my iOS implementation which works just fine. And of course it can't be decrypted without error. In fact the resulting file will have 0 bytes of size.

I am hoping someone can point out the error in my code to me. That would really be great.

@Duncan:

Thank you. I looked into that but I'm not really sure about all the steps I have to take. Especially what they mean in code. Maybe somebody could help me out here. Thanks a lot!

Encryption

  1. Generate a random encryption salt
  2. Generate the encryption key using PBKDF2 (see your language docs for how to call this). Pass the password as a string, the random encryption salt, and 10,000 iterations.
  3. Generate a random HMAC salt
  4. Generate the HMAC key using PBKDF2 (see your language docs for how to call this). Pass the password as a string, the random HMAC salt, and 10,000 iterations.
  5. Generate a random IV
  6. Encrypt the data using the encryption key (above), the IV (above), AES-256, and the CBC mode. This is the default mode for almost all AES encryption libraries.
  7. Pass your header and ciphertext to an HMAC function, along with the HMAC key (above), and the PRF "SHA-256" (see your library's docs for what the names of the PRF functions are; this might also be called "SHA-2, 256-bits").
  8. Put these elements together in the format given above.
1

There are 1 answers

5
erdeszt On

Encrypt the data using the encryption key (above), the IV (above), AES-256, and the CBC mode. This is the default mode for almost all AES encryption libraries.

This is a false assumption, according to this sjcl uses ccm as a default mode.