In the below code there might arise a question why we need to do hashing and extract the final secret key from it. The importance of this step could be felt incase we are storing passwords in DBs instead of directly using actual secret key and hashing, the hashing by using message digest adds more strength.

EncryptUtil.java

package com.mugil.org;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class EncryptUtil {
    private static SecretKeySpec secretKey;
    private static byte[] key;

    public static void setKey(String myKey) {
        MessageDigest sha = null;
        try {
            //Byte Arrays are secured compared to storing in String as it is immutable
            key = myKey.getBytes("UTF-8");

            /*
              MessageDigest class represents a cryptographic hash function which can calculate a
              message digest from binary data.A hash function is a mathematical function that 
              converts a numerical input value into another compressed numerical value.The input to 
              the hash function is of arbitrary length but output is always of fixed length.
              Values returned by a hash function are called message digest or simply hash values.
            */

            /*
              Code will work without below two lines but hashing adds more strength to secret key
              AES needs a 128/192/256 bits key. If you don't hash your key and only trim the input it
              would only use the first 16/24/32 Bytes. So generating a Hash is the only reasonable way.
             */
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);

            /*Use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).*/
            key = Arrays.copyOf(key, 16);

            /*Taking Key that would be used for Encrytion */
            secretKey = new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String strToEncrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
}

SimpleEncryption.java

package com.mugil.org;

public class SimpleEncryption {
    public static void main(String[] args) {
        final String secretKey = "ItSecretKey";

        String originalString = "You Nailed It!!!";
        String encryptedString = EncryptUtil.encrypt(originalString, secretKey) ;
        String decryptedString = EncryptUtil.decrypt(encryptedString, secretKey) ;

        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}

You Nailed It!!!
lFY4a0e0BRVfcfko56Lpe78iUfPoZm5wkq/zv0hrFco=
You Nailed It!!!

Comments are closed.