Using CCHmac for creating message authentication codes

This is a second part of the first post about hashing data using SHA256. Here we will look into CCHmac (Hash-based Message Authentication Code) functions and see how to use it for creating authentication codes what can be used for data integrity checks and authentication of a message.

Message authentication codes

Hash-based message authentication code enables validating messages sent between two parties. For achieving that, the sender will use secret key for creating an authentication code of the message. Then transmits the message and the code to the other party. Then the receiver will use the same secret key (only they both know the key) for creating an authentication code of the received message. If the received authentication code matches with the created one, the receiver can be sure of the message’s integrity.

CCHmac interface

There are 3 functions which are used together for creating an authentication code. These are: CCHmacInit(), CCHmacUpdate() and CCHmacFinal(). Note that the update function can be called multiple times for processing the data in chunks. In addition, there is a convenience function what internally creates CCHmacContext object and uses listed functions for initialising, updating and finalising the process of creating an authentication code. We will concentrate on the convenience function.

Arguments define the hashing algorithm, secret key, input data and an output buffer. It is important to note that the output buffer needs to be preallocated and the length depends on the chosen algorithm (for example SHA256 requires a buffer with length equal to CC_SHA256_DIGEST_LENGTH).

Data extension for CCHmac in Swift

The method for creating authentication code is func authenticationCode(for algorithm: Algorithm, secretKey: Data) -> Data what is very easy to use for creating raw message authentication code. It can be converted into string by using Data's base64EncodedString().

Example project can be found on GitHub (CommonCryptoExample).

References

Wikipedia: HMAC
man page of CCHmac

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s