Thursday, September 8, 2016

How-To encrypt a file in Java

Encrypting files in Java is easy! Typically it would require loads of boilerplate that only increases the chance of doing something wrong, thus breaking security. Luckily there are safe and sound libraries that can help us perform the task at hand with relative ease.

One of these is Encryptor4j. Download and include it in your project before the next step.

Encrypting a file would be as simple as this:
// We use a password based key here.
// Other options are available too: check the documentation
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);
By default, this would encrypt the file using AES with 128-bit keys using CTR mode. If however Unlimited Strength Jurisdiction Policy files are installed it would be encrypted with the maximum key length of 256-bits.

The key is generated from the password using 65536 salted hashing iterations. If you need to regenerate the key from the password in another language check out the KeyFactory implementation used internally by the FileEncryptor class.

Decrypting the file is easy too (it's almost identical to encrypting):
File srcFile = new File("original.zip.encrypted");
File destFile = new File("decrypted.zip");
String password = "mysupersecretpassword";
FileEncryptor fe = new FileEncryptor(password);
fe.decrypt(srcFile, destFile);
This about sums it up. Why reinvent the wheel if an existing library can choose the right block mode, key length and generates and prepends IVs transparently for your convenience.

No comments:

Post a Comment