Question

I'm trying to add the additional authenticated data (AAD) to AES-GCM on Android. I see the Java 7 version of Cipher notes about using GCMParameterSpec and the updateAAD(...) method but given Android is Java 6 based I'm all out of ideas. I'm using Spongycastle as the crypto library

  GCMParameterSpec s = new GCMParameterSpec(...);
  cipher.init(..., s);
  cipher.updateAAD(...);  // AAD
Was it helpful?

Solution

thanks @andrey - I found a more complete sample also form the BC mailing list

public void testGCM() {
    try {
        byte iv[] = "123456789012".getBytes();
        byte inMsg[] = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
                .getBytes();
        byte aad[] = "123456789012123456789012123456789012345678901234567890123456"
                .getBytes();
        byte key[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".getBytes();

        System.out.println("inMsgLen===" + inMsg.length);

        // encrypt
        AEADParameters parameters = new AEADParameters(
                new KeyParameter(key), 128, iv, aad);
        GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
        gcmEngine.init(true, parameters);

        byte[] encMsg = new byte[gcmEngine.getOutputSize(inMsg.length)];
        int encLen = gcmEngine.processBytes(inMsg, 0, inMsg.length, encMsg,
                0);
        encLen += gcmEngine.doFinal(encMsg, encLen);

        System.out.println("encLen===" + encLen);

        // decrypt
        gcmEngine.init(false, parameters);

        byte[] decMsg = new byte[gcmEngine.getOutputSize(encMsg.length)];
        int decLen = gcmEngine.processBytes(encMsg, 0, encMsg.length,
                decMsg, 0);
        decLen += gcmEngine.doFinal(decMsg, decLen);

        System.out.println("decLen===" + decLen);

        System.out.println("MSG===" + new String(decMsg));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

OTHER TIPS

From BC mailing list:

It seems an oversight on our part means the JCE provider does not currently expose a mechanism for setting the AAD (also applies to other AEAD ciphers: CCM, EAX).

In the lightweight API, the AAD is passed to the cipher (.init) via an instance of AEADParameters (the field 'associatedText').

With lightweight API you can also provide AAD data via processAADBytes() method exposed by AEADBlockCipher interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top