Encryption and decryption are fundamental requirements of every secure-aware application, therefore the Java platform provides strong support for encryption and decryption through its Java Cryptographic Extension (JCE) framework which implements the standard cryptographic algorithms such as AES, DES, DESede and RSA. This tutorial shows you how to basically encrypt and decrypt files using the Advanced Encryption Standard (AES) algorithm. AES is a symmetric-key algorithm that uses the same key for both encryption and decryption of data.
1. Basic Steps
Here are the general steps to encrypt/decrypt a file in Java:
- Create a Key from a given byte array for a given algorithm.
- Get an instance of Cipher class for a given algorithm transformation. See document of the Cipher class for more information regarding supported algorithms and transformations.
- Initialize the Cipher with an appropriate mode (encrypt or decrypt) and the given Key.
- Invoke doFinal(input_bytes) method of the Cipher class to perform encryption or decryption on the input_bytes, which returns an encrypted or decrypted byte array.
- Read an input file to a byte array and write the encrypted/decrypted byte array to an output file accordingly.
Now, let’s see some real examples.
2. The CryptoUtils class
Here’s a utility class that provides two utility methods, one for encrypt a file and another for decrypt a file:
Both the methods encrypt() and decrypt() accepts a key, an input file and an output file as parameters, and throws aCryptoException which is a custom exception written as below:
This custom exception eliminates the messy throws clause, thus make the caller invoking those methods without catching a lengthy list of original exceptions.
3. The CryptoUtilsTest class
The following code is written for a test class that tests the CryptoUtils class above:
This test program simply encrypts a text file, and then decrypts the encrypted file. Note that the key used for encryption and decryption here is a string “Mary has one cat”;
4. Note about key size
The AES algorithm requires that the key size must be 16 bytes (or 128 bit). So if you provide a key whose size is not equal to 16 bytes, a java.security.InvalidKeyException will be thrown. In case your key is longer, you should consider using a padding mechanism that transforms the key into a form in which its size is multiples of 16 bytes. See the Cipher class Javadoc for more details.References