# How to hash a structure that needs to include that hash's outcome?

so I am busy writing a TCP protocol in which I send a "packet header" with each packet of data. This packet header is a structure that contains information about the data that was sent. I want to verify whether the header was tampered with in some manner and I am thinking of using a hash of the header to ensure it was not tampered with. I want to know if it is possible to include this hash in the header itself. Here is what the packet header looks like.

struct PACKET_HEADER
{
DWORD dwMagic;
BYTE lpvChecksum[32];

... Rest of header follows


I am not sure if this method will work and I am open to any other suggestions on how to verify the header.

Thanks

-

First, a hash does not provide integrity. You would need a MAC (like HMAC) or a digital signature to ensure the message hasn't changed in transit.

You'll have to put some standard value (say all zeros) into the field which holds the MAC, compute the MAC, then insert the value. Otherwise you have a chicken and egg problem. You need the MAC value to compute the MAC value. So which comes first the MAC or the header you want to compute the MAC over. See the issue?

To verify the MAC, the receiver would pull out the MAC tag, replace it with all zeros (or whatever you used), compute what the MAC should be, compare with the extracted tag.

If you are not restricted to the header as defined, placing the buffer for the MAC at the end of the header would be the best. That way you can just MAC the data before the MAC slot.

-
Was about to ask what the difference between a hash and a MAC but found it. For all those interested (security.stackexchange.com/questions/1873/…) –  Keagan Ladds May 7 '13 at 15:06
@mikeazo, if you're going to all that trouble of swapping the checksum, you may as well put the MAC at the end of the structure and omit it from the computation entirely. It's less complexity, less moving parts, less to incorrectly implement, and therefore more secure. –  John Deters May 7 '13 at 17:51
@JohnDeters, I totally agree and should have put that in the answer. –  mikeazo May 7 '13 at 20:01