The scenario is this: I have a client and server talking. Here is the standard idea:
- Use Diffie-Hellman to generate a secret key between the client and server.
- Use this secret key for AES/CTR/PKCS7Padding cipher on both client and server.
- Use Hmac on the original message
- Encrypt the Hmac message with AES cipher
So this would allow the client and server to talk securely.
The relevant code example I'm looking at is the tutorial here: Tampered message with HMac, encryption with AES in CTR mode : Advanced Encryption Standard « Security « Java Tutorial
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.
Here is the section I'm confused on:
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()];
If the client sends an encrypted message, how does the server retrieve the ivSpec, hMac.getMacLength(), and hMacKey? These items are required on the server to decrypt the message from the client.
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.
On a last note, can someone explain what the purpose of this line is? Is this for encryption or decryption?
cipherText[9] ^= '0' ^ '9';`