HMAC and Key Derivation

Simply calculating **insecure** (see the details). It is recommended to use the **HMAC algorithm instead**, e.g.

`hash_func(key + msg)`

to obtain a MAC (message authentication code) is considered `HMAC-SHA256`

or `HMAC-SHA3-512`

or other secure MAC algorithm.What is HMAC?

â€‹**HMAC** = **H**ash-based **M**essage **A**uthentication **C**ode (MAC code, calculated using a cryptographic hash function):

HMAC(key, msg, hash_func) -> hash

The results MAC code is a **message hash** mixed with a secret key. It has the cryptographic properties of hashes: **irreversible**, **collision resistant**, etc.

The

`hash_func`

can be any cryptographic hash function like `SHA-256`

, `SHA-512`

, `RIPEMD-160`

, `SHA3-256`

or `BLAKE2s`

.Key Derivation Functions (KDF)

function(password) -> key

As **very simple KDF function**, we can use SHA256: just hash the password. Don't do this, because it is **insecure**. Simple hashes are vulnerable to **dictionary attacks**.

As more complicated KDF function, you can derive a password by calculating **HMAC(salt, msg, SHA256)** using some random value called "**salt**", which is stored along with the derived key and used later to derive the same key again from the password.

HMAC Calculation - Example

To get a better idea of **HMAC** and how it is calculated, try this online tool: https://www.freeformatter.com/hmac-generator.htmlâ€‹

Play with calculating **HMAC('sample message', '12345', 'SHA256')**:

HMAC('sample message', '12345', 'SHA256') =

'ee40ca7bc90df844d2f5b5667b27361a2350fad99352d8a6ce061c69e41e5d32'

Try the above example yourself.

Last modified 11mo ago

Copy link

On this page

What is HMAC?

Key Derivation Functions (KDF)

HMAC Calculation - Example