2

I'm Encrypting the data with "AES/GCM/NoPadding" algorithm, before cipher init method I'm getting java.security.InvalidAlgorithmParameterException: GCM can not be used with class javax.crypto.spec.GCMParameterSpec error, is there any specific reason for this??

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, parameterSpec);

2 Answers2

1

It seems you have to use the IAIK specific "GCMParameterSpec" and not the Java "JCE-own". I assume that your IDE has automatically choose the JCE one because you are using only 2 parameters ("128" and iv).

Regarding the IAIK-Javadocs http://javadoc.iaik.tugraz.at/iaik_jce/old/iaik/security/cipher/GCMParameterSpec.html I can see that there are four constructors but none of the one with 2 parameters needs aadata and nonce:

Constructor and Description

GCMParameterSpec() Creates a GCM Parameter specification with default values.

GCMParameterSpec(byte[] aaData, byte[] nonce) Creates a GCM Parameter specification with the given additional data and nonce.

GCMParameterSpec(byte[] aaData, byte[] nonce, byte[] macBlock) Creates a GCM Parameter specification with the given additional data, nonce and MAC block.

GCMParameterSpec(byte[] aaData, byte[] nonce, int macLen) Creates a GCM Parameter specification with the given additional data, nonce and MAC length.

So I think you could use:

GCMParameterSpec(byte[] aaData, byte[] nonce, int macLen)

and with your data

GCMParameterSpec(null, iv, 128)
Michael Fehr
  • 5,827
  • 2
  • 19
  • 40
-3

Try this something like this:

try {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] key = f.generateSecret(spec).getEncoded();
        byte[] iv = "iv".getBytes();

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, parameterSpec);

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
ognjenkl
  • 1,407
  • 15
  • 11