How to Encrypt and Decrypt using AES in Java

Below is a working class on how to encrypt and decrypt using AES in Java. Aside from using the javax.crypto package, you should also add the apache commons code dependency. You can download and import the jar file to your dependency or add it to your maven pom:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

The apache commons codec Base64 methods were used to encode/decode string. The keys were hard coded to prevent anyone to get the keys and use to decrypt string.
{adinsert between_post_text}
Below is the example class of EncryptDecrypt.java. Change SECRET_KEY_1 and SECRET_KEY_2 to your own secret keys.

package com.javapointers;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class EncryptDecrypt {

    private static final String SECRET_KEY_1 = "ssdkF$HUy2A#D%kd";
    private static final String SECRET_KEY_2 = "weJiSEvR5yAC5ftB";

    private IvParameterSpec ivParameterSpec;
    private SecretKeySpec secretKeySpec;
    private Cipher cipher;

    public EncryptDecrypt() throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
        ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes("UTF-8"));
        secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");
        cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    }


    /**
     * Encrypt the string with this internal algorithm.
     *
     * @param toBeEncrypt string object to be encrypt.
     * @return returns encrypted string.
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String encrypt(String toBeEncrypt) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(toBeEncrypt.getBytes());
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * Decrypt this string with the internal algorithm. The passed argument should be encrypted using
     * {@link #encrypt(String) encrypt} method of this class.
     *
     * @param encrypted encrypted string that was encrypted using {@link #encrypt(String) encrypt} method.
     * @return decrypted string.
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String encrypted) throws InvalidAlgorithmParameterException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.decodeBase64(encrypted));
        return new String(decryptedBytes);
    }
}

Remember to always use the same keys when trying to decode to avoid getting different value from the one that was encoded. So that is how to encrypt and decrypt using AES in Java.

How to Get Keys in Map

The sample code below demonstrate how to get keys in map, whether its a hashmap or any implementation of Map. The method in Map that will get keys is:

keySet();


This method will return a Set of object T where T is the type of object you have define to be the Keys when you initiliaze the Map.
Below is the actual implementation on how to get all keys in map using keySet() method.

public class MapKeys {

    private static Map<String, Person> map;

    public static void main(String[] args) {
        map = new HashMap<>();
        map.put("Sed", new Person());
        map.put("Joe", new Person());
        map.put("Richard", new Person());

        Set<String> keys = map.keySet();
        for(String key: keys) {
            System.out.println(key);
        }
    }
}

Note that the order of keys that was retrieve may be different from the order when you put the objects in Map.

Java Enumeration Tutorial and Example

This post is all about Java Enumeration Tutorial. Java Enumeration or java enum act like a constant variable with additional functionality.

For example, you may want to create a constant for gender. If you don’t know how to use enum, probably you will just define an integer constant for male and female values:

public static final int MALE = 1;
public static final int FEMALE = 2;

With enum, you can define it like this:

public enum Gender {
    MALE, FEMALE
}


That’s the very basic creation of enum. You can now use it just as how you use a constant variable. But what if you want to add property to the enum such as integer so that you can save the value in database? Enum can have constructor where you can define the property:

public enum Gender {
    MALE(1), FEMALE(2);

    private int code;
    
    Gender(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

In the above code, we define the constructor to take an integer parameter. We define the argument in our declaration of enum eg. 1 for MALE and 2 for FEMALE. Take note of the semicolon after FEMALE(2):

FEMALE(2);

It is necessary to add semicolon after the declarations of the enum if you have more codes after the declarations.

Now what if you want to get an instance of the enum based on the code? One implementation could be like this:

public enum Gender {
    MALE(1), FEMALE(2);

    private int code;
    private static Map genderMap;

    Gender(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static Gender getGender(int code) {
        if (genderMap == null) {
            genderMap = new HashMap();
            genderMap.put(1, Gender.MALE);
            genderMap.put(2, Gender.FEMALE);
        }
        return genderMap.get(code);
    }
}


Take note that we make it static method and field. Consider Java Enumeration as a class that also act like a constant. Below is an example of java enumeration usage.
Person.java

public class Person {
    private Gender gender;

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }
}

Main method:

public static void main(String[] args) {
        Person person1 = new Person();
        person1.setGender(Gender.MALE);

        Person person2 = new Person();
        person2.setGender(Gender.FEMALE);

        System.out.println("First Person Gender: " + person1.getGender() + ", code = " + person1.getGender().getCode());
        System.out.println("Second Person Gender: " + person2.getGender() + ", code = " + person2.getGender().getCode());
    }

The output will be:
java-enum-example

How to Sort List in Java

Below is an example on how to sort list in java. In order to sort list in java, the object inside the list should implement Comparable interface and we will use Collections utility class in Java. Implementing the Comparable interface gives you the flexibility to write your own logic on how the sorting will be done.

Basically, return a negative integer if you want this object to be on top or first in the list compared to the passed object, return 0 if both objects are the equal, and return positive integer if you want the passed object to be added first in the list before this object. Much better if we take an example:

Assuming we have List of object A, and we want to sort the list based on the integer property of object A in ascending.

public class A implements Comparable<A> {
    private int code;

    public A(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    @Override
    public int compareTo(A object) {
        if (this.code > object.getCode()) {
            return 1;
        } else if (this.code < object.getCode()) {
            return -1;
        } else {
            return 0;
        }
    }
}

Then, if we create objects of A and them to list, then use Collections.sort() method, the list will be sorted based on the implementation of Comparable interface.

public class SortList {

    public static void main(String[] args) {
        A a1 = new A(1);
        A a2 = new A(2);
        A a3 = new A(3);
        A a4 = new A(4);

        List<A> list = new ArrayList<A>();
        list.add(a3);
        list.add(a1);
        list.add(a4);
        list.add(a2);

        //sort the list
        Collections.sort(list);
        for(A a: list) {
            System.out.println(a.getCode());
        }
    }
}

The output would be:

1
2
3
4

How to Zip Files in Java

Below is an example on how to zip files in Java. You can also select multiple files and add to zip file. In this method, pass the name of the zip that you want to be created. The zip file will be save in the temporary folder of your computer. This method will return the zip file which you can save anywhere or do something else. This throws IOException if the file you want to add in zip throws an error.

    /**
     * Zip the files and add those in the temp location with the zip file name provided.
     *
     * @param zipFileName file name of the zip file to be set. File name should be complete with .zip extension
     * @param addToZip    files to be compress and added to the zip
     * @return zip file the zip file that was created
     * @throws IOException
     */
    public static File zipFiles(String zipFileName, List<File> addToZip) 
             throws IOException {

        String zipPath = System.getProperty("java.io.tmpdir") 
             + File.separator + zipFileName;
        new File(zipPath).delete(); //delete if zip file already exist

        try (FileOutputStream fos = new FileOutputStream(zipPath);
             ZipOutputStream zos = new ZipOutputStream(
                  new BufferedOutputStream(fos))) {
            zos.setLevel(9); //level of compression

            for (File file : addToZip) {
                if (file.exists()) {
                    try (FileInputStream fis = new FileInputStream(file)) {
                        ZipEntry entry = new ZipEntry(file.getName());
                        zos.putNextEntry(entry);
                        for (int c = fis.read(); c != -1; c = fis.read()) {
                            zos.write(c);
                        }
                        zos.flush();
                    }
                }
            }
        }
        File zip = new File(zipPath);
        if (!zip.exists()) {
            throw new FileNotFoundException("The created zip file could not be found");
        }
        return zip;
    }