How to Use AES for Encryption and Decryption in Java

Learn how to use AES for encryption and decryption in Java

โ€œThereโ€™s as many atoms in a single molecule of your DNA as there are stars in the typical galaxy. We are, each of us, a little universe.โ€ โ€• Neil deGrasse Tyson, Cosmos

1. Introduction

The Advanced Encryption Standard (AES) is a standard for encryption and decryption that has been approved by the U.S. NIST (National Institute of Standards and Technology) in 2001. It is more secure than the previous encryption standard DES (Data Encryption Standard) and 3DES (Triple-DES). You should be using AES for all symmetric encryption needs in preference to DES and 3DES (which are now deprecated).

Symmetric Encryption refers to algorithms that use the same key for encryption as well as decryption. As such, the key should be kept secret and must be exchanged between the encryptor and decryptor using a secure channel.

The core java libraries provide good support for all aspects of encryption and decryption using AES so no external libraries are required. In this article, we show you how to properly perform encryption and decryption using AES with just the core java API.

[Note: Check out how to use AES for file encryption and decryption in python.]

2. The Imports

We need the following import statements for the program.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;

3. Generate an Initialization Vector (IV)

When using AES with a mode known as CBC (Cipher Block Chaining), you need to generate an initialization vector (IV). In the CBC mode, each plaintext block is XORed with the previous ciphertext block before being encrypted. So you need an initialization vector for the first block. To produce different ciphertext with each run of the encryption (even with the same plaintext and key), we use a random initialization vector.

To generate the IV, we use the SecureRandom class. The block size required depends on the AES encryption block size. For the default block size of 128 bits, we need an initialization vector of 16 bytes.

From the initialization vector, we create an IvParameterSpec which is required when creating the Cipher.

byte[] iv = new byte[128/8];
srandom.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);

You can save the initialization vector for transmission along with the ciphertext as follows. This file can be transmitted plainly i.e. no encryption is required.

String ivFile = ...;
try (FileOutputStream out = new FileOutputStream(ivFile)) {
    out.write(iv);
}

4. Generating or Loading a Secret Key

If you do not already have a key, you should generate one as follows:

KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey skey = kgen.generateKey();

If you have a key (maybe one generated previously and stored securely), you can load it from a binary key file using the following code:

String keyFile = ...;
byte[] keyb = Files.readAllBytes(Paths.get(keyFile));
SecretKeySpec skey = new SecretKeySpec(keyb, "AES");

If you need to save a generated key for future usage (maybe for loading using the above code), you can do it as follows:

String keyFile = ...;
try (FileOutputStream out = new FileOutputStream(keyFile)) {
    byte[] keyb = skey.getEncoded();
    out.write(keyb);
}

5. Creating the Cipher

The Cipher object is the one that handles the actual encryption and decryption. It needs the secret key and the IvParameterSpec created above.

When encrypting, create the Cipher object as follows:

Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);

For decryption, you need to load the initialization vector and create the IvParameterSpec.

String ivFile = ...;
byte[] iv = Files.readAllBytes(Paths.get(ivFile));
IvParameterSpec ivspec = new IvParameterSpec(iv);

Now you can create the Cipher object:

Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.DECRYPT_MODE, skey, ivspec);

6. Encrypting a String

Once the Cipher object is created, you can perform the encryption. The encryption process works with byte arrays.

To encrypt a String, first convert it to a byte array by encoding it in UTF-8. Then write the data to a file as follows:

String plainText = ...;
String outFile = ...;
try (FileOutputStream out = new FileOutputStream(outFile)) {
    byte[] input = plainText.getBytes("UTF-8");
    byte[] encoded = ci.doFinal(input);
    out.write(encoded);
}

7. Decrypting Back to a String

Read back encrypted text and convert it to a String as follows:

String inFile = ...;
byte[] encoded = Files.readAllBytes(Paths.get(inFile));
String plainText = new String(ci.doFinal(encoded), "UTF-8");

8. Encrypting a File

The procedure for encrypting a file is a bit more involved. Read the input data in a loop and invoke Cipher.update(). If a byte array is returned, you can write it to the output file. Finally wrap up with a Cipher.doFinal().

static private void processFile(Cipher ci,String inFile,String outFile)
    throws javax.crypto.IllegalBlockSizeException,
           javax.crypto.BadPaddingException,
           java.io.IOException
    {
        try (FileInputStream in = new FileInputStream(inFile);
             FileOutputStream out = new FileOutputStream(outFile)) {
            byte[] ibuf = new byte[1024];
            int len;
            while ((len = in.read(ibuf)) != -1) {
                byte[] obuf = ci.update(ibuf, 0, len);
                if ( obuf != null ) out.write(obuf);
            }
            byte[] obuf = ci.doFinal();
            if ( obuf != null ) out.write(obuf);
        }
    }

Invoke the encryption as follows:

Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
processFile(ci, inFile, outFile);

9. Decrypting a File

The outfile obtained from the above procedure can be decrypted quite simply by specifying the decrypt mode as follows:

Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.DECRYPT_MODE, skey, ivspec);
processFile(ci, inFile, outFile);

And that covers the whole story of encryption and decryption using AES.

Conclusion

The process for encrypting and decrypting using AES is a bit involved. First you generate an IV (initialization vector) and then generate (or load) a secret key. Next you create a cipher object which you can use for encryption and decryption.

7 thoughts on “How to Use AES for Encryption and Decryption in Java”

  1. Thanks for the tutorial. Can you maybe show the complete .java file that you use? Because I am wondering whether everything is in 1 class, or you have a seperate encrypt and decrypt class?

  2. While decryption The first line is not properly decrypted rest of the data is fine, could you please help me how to resolve that, thanks

  3. My good sir. If you do not mind i would like for you to deliver us the full source code, for us to study. If you do not want to, can you at least point us in a direction where we can find a full tutorial on how to code AES file encryption in java? That would be much appreciated. ๐Ÿ™‚

Leave a Reply to Stephan Gunter Cancel reply

Your email address will not be published. Required fields are marked *