AES-128 Example in JAVA

The example given will accomplish below Tasks.

  • Generate symmetric key using AES-128.
  • Generate initialization vector used for CBC (Cipher Block Chaining).
  • Encrypt message using symmetric key and initialization vector.
  • Decrypt the encrypted message using symmetric key and initialization vector.

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

public class AESManager {

 public static String ALGORITHM = "AES";
 private static String AES_CBS_PADDING = "AES/CBC/PKCS5Padding";

 public static byte[] encrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  return AESManager.encryptDecrypt(Cipher.ENCRYPT_MODE, key, IV, message);

 public static byte[] decrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  return AESManager.encryptDecrypt(Cipher.DECRYPT_MODE, key, IV, message);

 private static byte[] encryptDecrypt(final int mode, final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  final Cipher cipher = Cipher.getInstance(AES_CBS_PADDING);
  final SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
  final IvParameterSpec ivSpec = new IvParameterSpec(IV);
  cipher.init(mode, keySpec, ivSpec);
  return cipher.doFinal(message);

 public static String getHex(byte[] data, int length) {
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < length; i++) {
   String hexStr = Integer.toHexString(((int) data[i]) & 0xFF);
   if (hexStr.length() < 2) {
   } else {
  return sb.toString();

} AESClient class will generate random input message and will invoke to encrypt & decrypt input message.
import java.util.Base64;
import java.util.UUID;

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

public class AESClient {

 private static int AES_128 = 128;
 private static int AES_192 = 192;
 private static int AES_256 = 256;

 public static void main(String[] args) throws Exception {

  byte keyBytes[] = generateKey();

  String AES_KEY_HEX = AESManager.getHex(keyBytes, keyBytes.length);
  System.out.println("AES-KEY : " +AES_KEY_HEX);

  // Initialization vector
  byte IVBytes[] = generateKey();

  String randomString = UUID.randomUUID().toString().substring(0, 16);
  System.out.println("1. Original Message: " + randomString);

  byte[] cipherText = AESManager.encrypt(keyBytes, IVBytes, randomString.getBytes());
  System.out.println("2. Encrypted Text: " + Base64.getEncoder().encodeToString(cipherText));

  byte[] decryptedString = AESManager.decrypt(keyBytes, IVBytes, cipherText);
  System.out.println("3. Decrypted Message : " + new String(decryptedString));

 public static byte[] generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
  KeyGenerator keyGenerator = KeyGenerator.getInstance(AESManager.ALGORITHM);
  SecretKey key = keyGenerator.generateKey();
  return key.getEncoded();
Sample outPut:
AES-KEY : 6239A5DBBA65D0D42E6520922621A8B8
1. Original Message: 5dbf850f-3938-48
2. Encrypted Text: smV12iTwLIHNTgFRSDzG2xmzYl5yRJQ6Jo2qnqK0iqc=
3. Decrypted Message : 5dbf850f-3938-48

GlobalPlatform Secure Channel Protocol - SCP02 and SCP03


GlobalPlatform (GP) is a cross industrial consortium that issues specifications about smart cards.

GP Card Specification

A set of technical documentation relating to the deployment and management of multiple applications on smart card.

Secure Channel Protocol (SCP)

An SCP is used to protect bidirectional communication between Java Card and Host. It is used as Mutual authentication and provide cryptographic protection for card and host subsequent communication.

SCP provides the following three levels of  security:

  • Mutual authentication
  • Data Integrity
  • Confidentiality

Mutual authentication

Mutual authentication is achieved through the process of initiating a Secure Channel and provides assurance to both; card and host, that they are communicating with an authenticated entity. This process include the creation of new challenges and secure channel session keys. If any step in the mutual authentication process fails, the process shall be restarted, i.e. new challenges and Secure Channel Session keys shall be generated again.

Data Integrity

Data or message integrity is checked by comparing C-MAC received from off-card entity (Host) with the card internally generated C-MAC. Note that this comparison is done using same Secure Channel session key, generated in Mutual authentication step.

Data Confidentiality

The date received from host to card or card to host is not viewable by an unauthorized entity rather it is encrypted with Secure Channel session key generated during the mutual authentication process.

Secure Channel Protocol '02'

SCP02 uses Triple DES encryption algorithm in CBC mode with Initialization vector (IV) of binary zeros. As SCP02 uses 3DES in CBC mode with fixed IV of binary zeros therefore its encryption scheme is deterministic and not highly secure and thus vulnerable to a classical plaintext-recovery attacks.

SCP02 relies on the «Encrypt-and-MAC» method, which means that it compute the MAC on the plain-text, encrypt the plain-text, and then append the MAC at the end of the ciphertext as shown in below diagram:

Encrypt-and-MAC Method

Secure Channel Protocol '03'

SCP03 uses Advanced Encryption Standard (AES) encryption algorithm with randomly generated Initialization vector (IV) and Hence its encryption scheme is un-deterministic and highly secure.

SCP03 relies on the «Encrypt-then-MAC» method, which means that it Encrypt the plain-text, then compute the MAC on the ciphertext, and append the MAC to the ciphertext as shown in below diagram:

Encrypt-then-MAC Method

SCP03 provides strong security guarantees, resistance to replay, out of order delivery and algorithm substitution attacks.

Why we need SCP03?

As the latest Java Cards have support for RSA above 2048, AES-128, AES-192, AES-256 and Elliptic-curve cryptography (ECC) (f=256 and above), SCP02 cannot be used to encrypt above keys types and hence such keys cannot be loaded using SCP02 mechanism. As a result GlobalPlatform provided a mechanism in the form of SCP03 by which such keys can be loaded into the cards.

Note: You can read more about SCP02 in GlobalPlatform Card Specification Version 2.1.1 Appendix E, while regarding SCP03 you can refer to GlobalPlatform Card Specification Version 2.2

Installation and setup of the Java Cryptography Extension (JCE)

Encryption mechanism is governed by laws of each country and often have restrictions on the strength of the encryption. Like in the United States, all encryption over 128-bit is restricted if the data is travelling outside the country.By default, the Java JCE implements a strength policy to comply with these rules. If a stronger encryption is preferred, and adheres to the laws of the country, then the JCE needs to have access to the stronger encryption policy. In other words, if you are planning on using AES 256-bit encryption, you must install the Unlimited Strength Jurisdiction Policy Files. Without these policies, 256-bit encryption is not possible.

In case of violating above rules get the exception Illegal key size or default parameters


" Key Size" error when invoking secured services.

The above exception usually occurs when we try to invoke the web services in a secured manner and your JVM is not provisioned for Java unlimited security jurisdiction policy.

So in order to provision for the Java unlimited security jurisdiction you must have to install Java Cryptography Extension (JCE) unlimited strength jurisdiction policy files.

Installation Steps

  • Go to the Oracle site
  • Download the version that matches your installed JVM. Like I have Java 7 installed so download
  • Unzip the folder and replace local_policy.jar and US_export_policy.jar in the path C:\Program Files\Java\jdk1.7.0_67\jre\lib\security.  (Note: these jars will be already there so you have to overwrite them)  
  • Simply restart your application to get rid of this exception.