# SHA256_HMAC for deriving session keys using a counter

I need to generate some session keys from a master key that was generated from an ECDH key exchange. The master key is 256 bits and I need 256 bit sessions keys.

Is it safe to use SHA256_HMAC with a counter as the HMAC input to get the session keys?

skey1 = SHA256_HMAC(master_key, 1);

skey2 = SHA256_HMAC(master_key, 2);

skeyN = SHA256_HMAC(master_key, N);

The counter is meaningful to the application to know which session key to use. I have also looked at Hashed Key Derivation Functions (HKDF) but it seems like that is more useful when you need a long random output from a given input. My output length is the same as the input length and I need to be able to generate the correct session key based on a counter value (might not be sequential calls). The counter is essentially an id.

Sure, that should be fine. It's probably more secure than KDF1 & 2 that use a normal hash method and a 4 byte counter. HKDF however can certainly be used for this, but it seems you only need to differentiate, rather than extract and expand.

• Anything missing from the answer, John? – Maarten Bodewes Jun 14 '15 at 11:47

Yes, it's fine.

However, you might as well use HKDF-Expand (with your counter as the context information 'info'), so that if you later need some session keys to be larger than 256 bits, the extension is already defined for you. So,

$$sk_1 = HMAC(mk, 1 || 0x01)\\ sk_2 = HMAC(mk, 2 || 0x01)\\ ...$$

And if you need a 512-bit $sk_3$ that's:

$$sk_3 = HMAC(mk, 3 || 0x01)\ ||\ HMAC(mk, HMAC(mk, 3 || 0x01) || 3 || 0x02)$$