Encrypting a large file with AES using JAVA

Don't even try to read entire large files into memory. Encrypt a buffer at a time. Just do the standard copy loop with a suitably initialized CipherOutputStream wrapped around the FileOutputStream. You can use this for all files, no need to make a special case out of it. Use a buffer of 8k or more.

EDIT The 'standard copy loop' in Java is as follows:

byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

where in this case out = new CipherOutputStream(new FileOutputStream(selectedFile), cipher).


You can also simplify the process even further using Encryptor4j that I have authored: https://github.com/martinwithaar/Encryptor4j

File srcFile = new File("original.zip");
File destFile = new File("original.zip.encrypted");
String password = "mysupersecretpassword";
FileEncryptor fe = new FileEncryptor(password);
fe.encrypt(srcFile, destFile);

This library uses streaming encryption so it will not cause OutOfMemoryError even with large files. Also, instead of using passwords you can use your own Key as well.

Check out the example on the Github page here: https://github.com/martinwithaar/Encryptor4j#file-encryption