After a long time, during which I was very busy by my personal project (building my house), I am come back with a simple article concerning the encrypting of message via the standard Cipher class. This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

In the following example, I will encrypt and decrypt a message via the symmetric algorithm “AES/ECB/PKCS5Padding” (via a secret key). A transformation is of the form “algorithm/mode/padding” or “algorithm”.

package com.ho.crypto.test1;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

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

 * Encrypt / Decrypt your message with Cipher Class.
 * @author huseyin
public class MyProtectorSingleton {

		// --------------------------------- PRIVATE ATTRIBUTES
		private static MyProtectorSingleton instance = null;
		private SecretKeySpec certificate = null;
		private Cipher aesEncrypt = null;
		private Cipher aesDecrypt = null;
		// ----------------------------------- CONSTRUCTORS
		private MyProtectorSingleton() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
			Random myRandom = new Random();
			byte[] myBytesArray = new byte[16];
			certificate = new SecretKeySpec(myBytesArray, 0, 16, "AES");
			aesEncrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
			aesEncrypt.init(Cipher.ENCRYPT_MODE, certificate);
			aesDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
		public static synchronized MyProtectorSingleton getInstance() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
			if(instance == null){
				instance = new MyProtectorSingleton();
			return instance;
		// ----------------------------- PUBLIC FUNCTIONS
		public byte[] protect(String toProtect) throws IllegalBlockSizeException, BadPaddingException{
			byte[] cipherText = aesEncrypt.doFinal(toProtect.getBytes());
			return cipherText;
		public String unprotect(byte[] toUnprotect) throws IllegalBlockSizeException, BadPaddingException{
			String cleartext = new String(aesDecrypt.doFinal(toUnprotect));
			return cleartext;
		public static void main(String[] args) {
				String toProtect = "this is my message";
				MyProtectorSingleton myProtector = MyProtectorSingleton.getInstance();
				byte[] msgProtected = myProtector.protect(toProtect);
				String str = myProtector.unprotect(msgProtected);
			}catch(Exception ex){

That’s all!!!!

Kind regards,