kabal
kabal

Reputation: 2145

crypto-js - read and decrypt file

I have some Java functions for doing AES encryption, one for a string, and one for a file

private static final String AES_CIPHER_METHOD = "AES";

public static SecretKeySpec createAesKeySpec(byte[] aesKey) {
    return new SecretKeySpec(aesKey, AES_CIPHER_METHOD);
}

public static String aesEncrypt(String data, SecretKeySpec aesKeySpec) throws EncryptionException {
    try {
        Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
        byte[] encVal = aesCipher.doFinal(data.getBytes("UTF8"));
        return new BASE64Encoder().encode(encVal);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException | BadPaddingException| IllegalBlockSizeException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
}

public static void aesEncryptFile(File in, File out, SecretKeySpec aesKeySpec) throws EncryptionException {
    try {
        Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);

        try (InputStream inputStream = new FileInputStream(in)) {
            try (OutputStream outputStream = new CipherOutputStream(new FileOutputStream(out), aesCipher)){
                IOUtils.copy(inputStream, outputStream);
            }
        }
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IOException e){
        throw new EncryptionException(e.getMessage(), e);
    }
}

I also have some tests to output some test data

private static final String KEY_STRING = "DpiA4l0gvb7biWZtiN6Vjg==";

private SecretKeySpec createKeySpec() {
    byte[] keyBytes = new Base64().decode(KEY_STRING.getBytes());
    return EncryptionUtils.createAesKeySpec(keyBytes);
}

public void testAesEncryptString() throws EncryptionException {
    String encryptedData = EncryptionUtils.aesEncrypt("A normal string", createKeySpec());
    System.out.println(encryptedData); //outputs 3XLwlSHWLm98teIoIS6QTA==
}

public void testAesEncryptStringFile() throws EncryptionException, IOException {
    File newFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile.txt"));
    FileUtils.writeStringToFile(newFile, "A string in a file");

    File encryptedFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile_encrypted.txt"));

    EncryptionUtils.aesEncryptFile(newFile, encryptedFile, createKeySpec());
}

I now need to implement decryption in javascript.

I have managed to successfully decrypt the plain string using crypto-js, however, I just cant get the file part working, and I cant quite see what is wrong

var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);

var aesOptions = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
};

var decryptedData = CryptoJS.AES.decrypt( "3XLwlSHWLm98teIoIS6QTA==", key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText ); //CORRECT outputs "A normal string"

var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";
$.get(encryptedFilename, function(data){
    console.log("encrypted file content", data);
    var encryptedData = CryptoJS.enc.Base64.parse(data);
    var decryptedData = CryptoJS.AES.decrypt( encryptedData, key, aesOptions);
    var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
    console.log( "decrypted file content = " + decryptedText ); //INCORRECT outputs "" SHOULD output "A string in a file"
});

link to jsfiddle - http://jsfiddle.net/pKNzV/46/

Upvotes: 4

Views: 6981

Answers (1)

kabal
kabal

Reputation: 2145

after a lot of trial and error, I was able to get this working.

the function base64ArrayBuffer comes from the following - https://gist.github.com/jonleighton/958841

var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);

var aesOptions = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
};

var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";

var oReq = new XMLHttpRequest();
oReq.open("GET", encryptedFilename, true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
   var data = oReq.response;
   if (data) {
      encodedData = base64ArrayBuffer(data);
      var decryptedData = CryptoJS.AES.decrypt( encodedData, key, aesOptions);
      var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
      console.log( "decryptedText = " + decryptedText );
      console.log("file decrypt successful: ", "A string in a file" === decryptedText);
   }
};

oReq.send(null);

Upvotes: 3

Related Questions