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);
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.