Line data Source code
1 : /*
2 : * HMAC-SHA256 KDF (RFC 5295)
3 : * Copyright (c) 2014, Jouni Malinen <j@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 146 : 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 146 : u8 iter = 1;
35 : const unsigned char *addr[4];
36 : size_t len[4];
37 : size_t pos, clen;
38 :
39 146 : addr[0] = T;
40 146 : len[0] = SHA256_MAC_LEN;
41 146 : addr[1] = (const unsigned char *) label;
42 146 : len[1] = os_strlen(label) + 1;
43 146 : addr[2] = seed;
44 146 : len[2] = seed_len;
45 146 : addr[3] = &iter;
46 146 : len[3] = 1;
47 :
48 146 : if (hmac_sha256_vector(secret, secret_len, 3, &addr[1], &len[1], T) < 0)
49 0 : return -1;
50 :
51 146 : pos = 0;
52 : for (;;) {
53 256 : clen = outlen - pos;
54 256 : if (clen > SHA256_MAC_LEN)
55 110 : clen = SHA256_MAC_LEN;
56 256 : os_memcpy(out + pos, T, clen);
57 256 : pos += clen;
58 :
59 256 : if (pos == outlen)
60 146 : break;
61 :
62 110 : if (iter == 255) {
63 0 : os_memset(out, 0, outlen);
64 0 : return -1;
65 : }
66 110 : iter++;
67 :
68 110 : if (hmac_sha256_vector(secret, secret_len, 4, addr, len, T) < 0)
69 : {
70 0 : os_memset(out, 0, outlen);
71 0 : return -1;
72 : }
73 110 : }
74 :
75 146 : return 0;
76 : }
|