You are here: Home » Using strong encryption in Java » Introduction

Using strong encryption in Java

Introduction

To be compliant with encryption export regulations, the standard Java (JDK and JRE) downloads are shipped with restricted security policy files. With these policy files in place, it is for example not possible to use the AES encryption algorithm with a key length of more than 128 bit.

The following sample uses a key length of 128 bit and properly encrypts and afterwards decrypts the given text "Hello World", using a vanilla Java 7 JRE installation:

package com.example;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class StrongAES {

    public void run() {
      try {
         String text = "Hello World";
         String key = "Bar12345Bar12345"; // 128 bit key

         // Create key and cipher
         Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
         Cipher cipher = Cipher.getInstance("AES");

         // encrypt the text
         cipher.init(Cipher.ENCRYPT_MODE, aesKey);
         byte[] encrypted = cipher.doFinal(text.getBytes());
         System.err.println(new String(encrypted));

         // decrypt the text
         cipher.init(Cipher.DECRYPT_MODE, aesKey);
         String decrypted = new String(cipher.doFinal(encrypted));
         System.err.println(decrypted);
      }catch(Exception e) {
         e.printStackTrace();
      }
    }

    public static void main(String[] args) {
       StrongAES app = new StrongAES();
       app.run();
    }
}