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:

package net.codejava.crypto;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * A utility class that encrypts or decrypts a file. 
 * @author www.codejava.net
 *
 */
public class CryptoUtils {
	private static final String ALGORITHM = "AES";
	private static final String TRANSFORMATION = "AES";

	public static void encrypt(String key, File inputFile, File outputFile)
			throws CryptoException {
		doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
	}

	public static void decrypt(String key, File inputFile, File outputFile)
			throws CryptoException {
		doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
	}

	private static void doCrypto(int cipherMode, String key, File inputFile,
			File outputFile) throws CryptoException {
		try {
			Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
			Cipher cipher = Cipher.getInstance(TRANSFORMATION);
			cipher.init(cipherMode, secretKey);
			
			FileInputStream inputStream = new FileInputStream(inputFile);
			byte[] inputBytes = new byte[(int) inputFile.length()];
			inputStream.read(inputBytes);
			
			byte[] outputBytes = cipher.doFinal(inputBytes);
			
			FileOutputStream outputStream = new FileOutputStream(outputFile);
			outputStream.write(outputBytes);
			
			inputStream.close();
			outputStream.close();
			
		} catch (NoSuchPaddingException | NoSuchAlgorithmException
				| InvalidKeyException | BadPaddingException
				| IllegalBlockSizeException | IOException ex) {
			throw new CryptoException("Error encrypting/decrypting file", ex);
		}
	}
}

Both the methods encrypt() and decrypt() accepts a key, an input file and an output file as parameters, and throws a CryptoException which is a custom exception written as below:

package net.codejava.crypto;

public class CryptoException extends Exception {

	public CryptoException() {
	}

	public CryptoException(String message, Throwable throwable) {
		super(message, throwable);
	}
}

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:

package net.codejava.crypto;

import java.io.File;

/**
 * A tester for the CryptoUtils class.
 * @author www.codejava.net
 *
 */
public class CryptoUtilsTest {
	public static void main(String[] args) {
		String key = "Mary has one cat1";
		File inputFile = new File("document.txt");
		File encryptedFile = new File("document.encrypted");
		File decryptedFile = new File("document.decrypted");
		
		try {
			CryptoUtils.encrypt(key, inputFile, encryptedFile);
			CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
		} catch (CryptoException ex) {
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
}

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:

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Attachments:
Download this file (SimpleFileEncryptionDecryptionDemo.zip)SimpleFileEncryptionDecryptionDemo.zip[Java source code]10 kB

Add comment

   


Comments 

#68Mats Järnmalm2023-08-28 18:00
This vill be interesting
Quote
#67pikachud2022-09-22 04:02
finally worked, have to state permission about write external storage in the manifest, and created three files (document.txt, document.encrypted, document.decrypted) in the device. Note that write something into the document.txt file. And the string key is "Mary has one cat", NOT "Mary has one cat1".
Quote
#66ikyahmad2021-09-04 08:30
pleass encrypt and decompile
Quote
#65nagasayankumar2021-08-29 21:00
Hi, I have used the logic to encrypt and decrypt my pdf file. It is working fine if encryption and decryption takes place in the same jvm. I am unable to decrypt the file on the other jvm even though I am using the same secret key and same code. Could you please guide me how to resolve the above issue.
Quote
#64hiba2021-07-29 22:55
iam having an error in file selected.
file is not found .what i have to do?plz reply as fast as possible
Quote