title: Confused how a client and a server using AES and Hmac will verify each other
body: <p>The scenario is this: I have a client and server talking. Here is the standard idea:</p>
  
  <ul>
  <li>Use Diffie-Hellman to generate a secret key between the client and server.</li>
  <li>Use this secret key for AES/CTR/PKCS7Padding cipher on both client and server.</li>
  <li>Use Hmac on the original message</li>
  <li>Encrypt the Hmac message with AES cipher</li>
  </ul>
  
  <p>So this would allow the client and server to talk securely. </p>
  
  <p>The relevant code example I'm looking at is the tutorial here: <a href="http://www.java2s.com/Tutorial/Java/0490__Security/TamperedmessagewithHMacencryptionwithAESinCTRmode.htm" rel="nofollow">Tampered message with HMac, encryption with AES in CTR mode : Advanced Encryption Standard « Security « Java Tutorial</a></p>
  
  <p>I'm able to generate the secret key for both the client and server. I'm able to encrypt this using Hmac and AES. Because encryption and decryption happen independently, I am unsure how to retrieve the relevant information required for decryption. </p>
  
  <p>Here is the section I'm confused on:</p>
  
  <pre><code>cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
  
  byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
  int messageLength = plainText.length - hMac.getMacLength();
  
  hMac.init(hMacKey);
  hMac.update(plainText, 0, messageLength);
  
  byte[] messageHash = new byte[hMac.getMacLength()];
  </code></pre>
  
  <p>If the client sends an encrypted message, how does the server retrieve the <code>ivSpec</code>, <code>hMac.getMacLength()</code>, and <code>hMacKey</code>? These items are required on the server to decrypt the message from the client.</p>
  
  <p>I understand that the Initialization Vector (IV) can be retained from the ciphertext since it's appended to the beginning of the resulting ciphertext (I think I'll have to add it in manually since I don't think AES cipher does that?). However, the hMacKey and hMac length used to verify the message integrity remains a mystery. </p>
  
  <p>On a last note, can someone explain what the purpose of this line is? Is this for encryption or decryption?</p>
  
  <pre><code>     cipherText[9] ^= '0' ^ '9';`
  </code></pre>