# How to calculate a hmac and cmac

I'm searching for a simple description that tells me in a schematic way how hmac and cmac is calculated. So far I found the following:

cmac = aes_encryption(hash(message), key)
hmac = hash(key, message)


The difference seems to be that cmacs are using a symmetric encryption additional to the hash-function while hmacs process the key within the hash-function itself. Is that correct?

Are there some situations when a cmac shall rather be used than a hmac?

• Whatever your source for hmac = hash(key, message), it's seriously incorrect. Even the commonly stated hmac = hash((key⊕opad) ∥ hash((key⊕ipad) ∥ message)) is an oversimplification (lacking output truncation, hash of key when it's above the hash internal block size…). I don't know exactly what's meant by cmac = aes_encryption(hash(message), key), but it does not look right to me either.
– fgrieu
Apr 2 at 11:54

The difference seems to be that cmacs are using a symmetric encryption additional to the hash-function while hmacs process the key within the hash-function itself. Is that correct?

There is no "normal" collision-resistant hash involved with CMAC. See below for details. For HMAC, the internals of the hash function are exploited to process the key, however it can use the hash function as a black box.

HMAC was standardized in RFC 2104 and NIST FIPS 198-1. The idea of HMAC is to exploit the common Merkle-Damgård structure of hash functions. This is done by first invoking the compression function with the pre-processed key, then using that state to process the message normally. Finally, the output of the previous step is used as a message again in the same manner as the original message was in the previous step, though this time with a different derived step.

CMAC is defined in NIST SP 800-38B which has a nice figure explaining the mode: Where the $$\oplus$$ denote XOR, CIPH is a block cipher, the MSB operation is truncation, $$K,K1,K2$$ are keys derived from the main input key via doubling in a polynomial field. The message is divided in blocks of at most CIPH's block size.

Are there some situations when a cmac shall rather be used than a hmac?

Yes, the typical recommendation is that if you either have hardware acceleration for a cipher or if you want to minimize code size and provide other functionality relying on a block cipher in your code.

• I've always wondered if there's a rationale to having two cases beyond saving one block encryption when the length is a multiple of the block size.
– fgrieu
Apr 2 at 14:37
• @fgrieu I'm pretty sure that saving a block cipher call is the rationale for the case distinction.
– SEJPM
Apr 2 at 14:41