authenticated encryption in Java 7

4.7k Views Asked by At

I want to use authenticated encryption in my code. According to the JDK, it seems that java 7 support AES/GCM/NoPadding.

However, I got the following error with the following code.

Error:

java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/GCM/NoPadding
    at javax.crypto.Cipher.getInstance(Cipher.java:524)
    at CipherService.main(CipherService.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Code:

Cipher c = Cipher.getInstance ("AES/GCM/NoPadding");
final int blockSize = c.getBlockSize();
final byte[] ivData = new byte[blockSize];
final SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG");
rnd.nextBytes(ivData);
GCMParameterSpec params = new GCMParameterSpec(blockSize * Byte.SIZE, ivData);
SecureRandom sr = new SecureRandom();
byte[] aesKey = new byte[KEY_SIZE];
byte[] ciphertext;
byte[] head = "Head".getBytes();
byte[] data = "Data".getBytes();
sr.nextBytes(aesKey);
SecretKeySpec sks = new SecretKeySpec(aesKey, "AES");
c.init(Cipher.ENCRYPT_MODE, sks, params);
c.updateAAD(head);
ciphertext = c.doFinal(data);
2

There are 2 best solutions below

1
On

You need to use an encryption provider such as BouncyCastle. Once you register it in your context, then you should be able to use any supported algorithm. Your other choice is to use the built in Sun/Oracle provided ones, but this violates the point of Java, being able to run the app on any JVM.

1
On

In short, you cannot (as Brett Pyke said). Because SunJCE crypto provider (and Oracle) does not include AES/GCM implementation. Thankfully, they included at least the GCMParameterSpec.

Your only two options (AFAIK) are crypto providers BouncyCastle and IAIK.

Edit/update: Oracle JDK-8 seems to provide a working implementation of AES/GCM.