Simple Example of Java Encryption Decryption

I am going to walk you through a really simple example showing how to encrypt and decrypt in java.

1. Create a maven project, here is the pom file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springriver</groupId>
	<artifactId>springriver.encryption.example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>EncryptionExample</name>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
	</dependencies>
</project>

2. Create a class to generate and save a key.

package com.springriver.example.encryption.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class KeyGeneratorUtil {

	/**
	 * @param args keyfile name
	 */

	public static void main(String args[]) throws NoSuchAlgorithmException,
			IOException {

		if (args.length < 1) {
			System.out.println("usage: java KeyGeneratorUtil filename");
			System.exit(0);
		}

		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		SecureRandom random = new SecureRandom(); 
		keyGen.init(random);
		SecretKey secretKey = keyGen.generateKey();
		FileOutputStream output = new FileOutputStream(args[0]);
		output.write(secretKey.getEncoded());
		output.close();

	}

}

3. execute this java class, “java com.springriver.example.mybatis.util.KeyGeneratorUtil key.key”
you should see a file “key.key” generated containing the key.

copy this key.key to the src/main/resources folder of this project

4. create an util class to encrypt and decrypt string

package com.springriver.example.encryption.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;

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

import org.springframework.core.io.ClassPathResource;

public class EncryptionUtil {
	private static SecretKeySpec skeySpec;
	
	static {	
		try {			
			ClassPathResource res = new ClassPathResource("key.key");
			if(res != null){
				File file = res.getFile();
				FileInputStream input = new FileInputStream(file);
				byte[] in = new byte[(int)file.length()];
				input.read(in);
				skeySpec = new SecretKeySpec(in, "AES");
				input.close();
			}
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static byte[] encrypt(String input) 
			throws GeneralSecurityException, NoSuchPaddingException{
	       Cipher cipher = Cipher.getInstance("AES");

	       cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
	       return cipher.doFinal(input.getBytes());
		
	}
	
	
	public static String decrypt(byte[] input) throws GeneralSecurityException, NoSuchPaddingException{
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		return new String(cipher.doFinal(input));
	}
	
}


the util class read in the key.key file from classpath, and generate a SecretKeySpec instance to be used for encryption or decryption.

both encrypt and decrypt methods will get the cipher first with algorithm “AES”, and init the cypher with the keySpec and mode (encrypt or decrypt), and with doFinal, generate the new encrypted/decrypted string.

Note: this example uses AES algorithm, you can certainly replace it with other algorithms. You have to be consistent though, the key generator, encrypt and decrypt methods have to use the same algorithm.

5. create a jnuit testing class to test out the EncryptionUtil methods.

package com.springriver.example.encryption;

import java.security.GeneralSecurityException;

import javax.crypto.NoSuchPaddingException;

import org.junit.Test;

import com.springriver.example.encryption.util.EncryptionUtil;

public class EncryptionUtilTest {
	@Test 
	public void testEncryptionDecryption(){
		String testString = "hello world";
		String resultString = "";
		try {
			resultString = EncryptionUtil.decrypt(EncryptionUtil.encrypt(testString));
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		assert(resultString != null);
		assert(resultString.equals(testString));
		
	}
}

Download the source code
springriver.encryption.example

Tagged with: , , ,
Posted in Encryption
One comment on “Simple Example of Java Encryption Decryption
  1. PumaRachel says:

    Thanks for the useful information. Need to add your blog to bookmarks

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>