sha256-prf.c revision 61d9df3e62aaa0e87ad05452fcb95142159a17b6
1/*
2 * SHA256-based PRF (IEEE 802.11r)
3 * Copyright (c) 2003-2007, 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#include "crypto.h"
14
15
16/**
17 * sha256_prf - SHA256-based Pseudo-Random Function (IEEE 802.11r, 8.5.1.5.2)
18 * @key: Key for PRF
19 * @key_len: Length of the key in bytes
20 * @label: A unique label for each purpose of the PRF
21 * @data: Extra data to bind into the key
22 * @data_len: Length of the data
23 * @buf: Buffer for the generated pseudo-random key
24 * @buf_len: Number of bytes of key to generate
25 *
26 * This function is used to derive new, cryptographically separate keys from a
27 * given key.
28 */
29void sha256_prf(const u8 *key, size_t key_len, const char *label,
30		const u8 *data, size_t data_len, u8 *buf, size_t buf_len)
31{
32	u16 counter = 1;
33	size_t pos, plen;
34	u8 hash[SHA256_MAC_LEN];
35	const u8 *addr[4];
36	size_t len[4];
37	u8 counter_le[2], length_le[2];
38
39	addr[0] = counter_le;
40	len[0] = 2;
41	addr[1] = (u8 *) label;
42	len[1] = os_strlen(label);
43	addr[2] = data;
44	len[2] = data_len;
45	addr[3] = length_le;
46	len[3] = sizeof(length_le);
47
48	WPA_PUT_LE16(length_le, buf_len * 8);
49	pos = 0;
50	while (pos < buf_len) {
51		plen = buf_len - pos;
52		WPA_PUT_LE16(counter_le, counter);
53		if (plen >= SHA256_MAC_LEN) {
54			hmac_sha256_vector(key, key_len, 4, addr, len,
55					   &buf[pos]);
56			pos += SHA256_MAC_LEN;
57		} else {
58			hmac_sha256_vector(key, key_len, 4, addr, len, hash);
59			os_memcpy(&buf[pos], hash, plen);
60			break;
61		}
62		counter++;
63	}
64}
65