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
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();
}
}