title: Checking tag and associated data in an AEAD cipher in Java
body: <p>I need to use AEAD to share information between two users, part of which must be encrypted and part of which should be kept in cleartext.</p>
  
  <p><em>Is there an API to check the ciphertext tag and access the associated data once a message has been encrypted with AES/GCM ?</em></p>
  
  <h2>In more detail:</h2>
  
  <p>I'm using Java 7 with bouncycastle as a provider and I have managed to encrypt and decrypt my data successfully, using the corresponding API:</p>
  
  <pre><code>private byte[] encrypt(SecretKey key, byte[] nonce, byte[] message, byte[] associatedData) throws ... {
     Cipher aeadCipher = Cipher.getInstance(AES_GCM_NOPADDING);
     aeadCipher.init(Cipher.ENCRYPT_MODE, kint, new GCMParameterSpec(GCM_MAC_SIZE, nonce);
     aeadCipher.updateAAD(associatedData);
     return aeadCipher.doFinal(message);
  }
  
  private byte[] decrypt(SecretKey key, byte[] nonce, byte[] cipherText, byte[] associatedData) throws ... {
     Cipher aeadCipher = Cipher.getInstance(AES_GCM_NOPADDING);
     aeadCipher.init(Cipher.DECRYPT_MODE, kint, new GCMParameterSpec(GCM_MAC_SIZE, nonce);
     aeadCipher.updateAAD(associatedData);
     return aeadCipher.doFinal(cipherText);
  }
  </code></pre>
  
  <p>However, it is my understanding that AES/GCM ciphertexts should already contain the parameters that could affect decryption (nonce and associatedData).
  Therefore, I would like to be able to retrieve them from the ciphertext, rather than having to store them alongside the ciphertext and pass them along to the decryption function. Furthermore, I'd like to be able to run integrity checks (computing the tag) and run some checks on the associated data without having to completely decrypt the message.</p>
  
  <p>Is there an API that would allow this and that I might have missed ?</p>
  
  <p>So far, I've checked:</p>
  
  <ul>
  <li>The Cipher API: <a href="http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html</a></li>
  <li>This very informative blog post on AES/GCM implementations in Java: <a href="http://blog.philippheckel.com/2014/03/01/cipherinputstream-for-aead-modes-is-broken-in-jdk7-gcm/" rel="nofollow">http://blog.philippheckel.com/2014/03/01/cipherinputstream-for-aead-modes-is-broken-in-jdk7-gcm/</a></li>
  </ul>