Line data Source code
1 : /*
2 : * TLS PRF P_SHA256
3 : * Copyright (c) 2011, 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 : * tls_prf_sha256 - Pseudo-Random Function for TLS v1.2 (P_SHA256, RFC 5246)
17 : * @secret: Key for PRF
18 : * @secret_len: Length of the key in bytes
19 : * @label: A unique label for each purpose of the PRF
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 TLS. This PRF is defined in RFC 2246, Chapter 5.
28 : */
29 0 : void tls_prf_sha256(const u8 *secret, size_t secret_len, const char *label,
30 : const u8 *seed, size_t seed_len, u8 *out, size_t outlen)
31 : {
32 : size_t clen;
33 : u8 A[SHA256_MAC_LEN];
34 : u8 P[SHA256_MAC_LEN];
35 : size_t pos;
36 : const unsigned char *addr[3];
37 : size_t len[3];
38 :
39 0 : addr[0] = A;
40 0 : len[0] = SHA256_MAC_LEN;
41 0 : addr[1] = (unsigned char *) label;
42 0 : len[1] = os_strlen(label);
43 0 : addr[2] = seed;
44 0 : len[2] = seed_len;
45 :
46 : /*
47 : * RFC 5246, Chapter 5
48 : * A(0) = seed, A(i) = HMAC(secret, A(i-1))
49 : * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + ..
50 : * PRF(secret, label, seed) = P_SHA256(secret, label + seed)
51 : */
52 :
53 0 : hmac_sha256_vector(secret, secret_len, 2, &addr[1], &len[1], A);
54 :
55 0 : pos = 0;
56 0 : while (pos < outlen) {
57 0 : hmac_sha256_vector(secret, secret_len, 3, addr, len, P);
58 0 : hmac_sha256(secret, secret_len, A, SHA256_MAC_LEN, A);
59 :
60 0 : clen = outlen - pos;
61 0 : if (clen > SHA256_MAC_LEN)
62 0 : clen = SHA256_MAC_LEN;
63 0 : os_memcpy(out + pos, P, clen);
64 0 : pos += clen;
65 : }
66 0 : }
|