Home | History | Annotate | Download | only in crypto
      1 /*
      2  * HMAC-SHA256 KDF (RFC 5295)
      3  * Copyright (c) 2014, Jouni Malinen <j (at) w1.fi>
      4  *
      5  * This software may be distributed under the terms of the BSD license.
      6  * See README for more details.
      7  */
      8 
      9 #include "includes.h"
     10 
     11 #include "common.h"
     12 #include "sha256.h"
     13 
     14 
     15 /**
     16  * hmac_sha256_kdf - HMAC-SHA256 based KDF (RFC 5295)
     17  * @secret: Key for KDF
     18  * @secret_len: Length of the key in bytes
     19  * @label: A unique label for each purpose of the KDF
     20  * @seed: Seed value to bind into the key
     21  * @seed_len: Length of the seed
     22  * @out: Buffer for the generated pseudo-random key
     23  * @outlen: Number of bytes of key to generate
     24  * Returns: 0 on success, -1 on failure.
     25  *
     26  * This function is used to derive new, cryptographically separate keys from a
     27  * given key in ERP. This KDF is defined in RFC 5295, Chapter 3.1.2.
     28  */
     29 int hmac_sha256_kdf(const u8 *secret, size_t secret_len,
     30 		    const char *label, const u8 *seed, size_t seed_len,
     31 		    u8 *out, size_t outlen)
     32 {
     33 	u8 T[SHA256_MAC_LEN];
     34 	u8 iter = 1;
     35 	const unsigned char *addr[4];
     36 	size_t len[4];
     37 	size_t pos, clen;
     38 
     39 	addr[0] = T;
     40 	len[0] = SHA256_MAC_LEN;
     41 	addr[1] = (const unsigned char *) label;
     42 	len[1] = os_strlen(label) + 1;
     43 	addr[2] = seed;
     44 	len[2] = seed_len;
     45 	addr[3] = &iter;
     46 	len[3] = 1;
     47 
     48 	if (hmac_sha256_vector(secret, secret_len, 3, &addr[1], &len[1], T) < 0)
     49 		return -1;
     50 
     51 	pos = 0;
     52 	for (;;) {
     53 		clen = outlen - pos;
     54 		if (clen > SHA256_MAC_LEN)
     55 			clen = SHA256_MAC_LEN;
     56 		os_memcpy(out + pos, T, clen);
     57 		pos += clen;
     58 
     59 		if (pos == outlen)
     60 			break;
     61 
     62 		if (iter == 255) {
     63 			os_memset(out, 0, outlen);
     64 			os_memset(T, 0, SHA256_MAC_LEN);
     65 			return -1;
     66 		}
     67 		iter++;
     68 
     69 		if (hmac_sha256_vector(secret, secret_len, 4, addr, len, T) < 0)
     70 		{
     71 			os_memset(out, 0, outlen);
     72 			os_memset(T, 0, SHA256_MAC_LEN);
     73 			return -1;
     74 		}
     75 	}
     76 
     77 	os_memset(T, 0, SHA256_MAC_LEN);
     78 	return 0;
     79 }
     80