3 * Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * Alternatively, this software may be distributed under the terms of BSD
12 * See README and COPYING for more details.
24 * tls_prf - Pseudo-Random Function for TLS (TLS-PRF, RFC 2246)
25 * @secret: Key for PRF
26 * @secret_len: Length of the key in bytes
27 * @label: A unique label for each purpose of the PRF
28 * @seed: Seed value to bind into the key
29 * @seed_len: Length of the seed
30 * @out: Buffer for the generated pseudo-random key
31 * @outlen: Number of bytes of key to generate
32 * Returns: 0 on success, -1 on failure.
34 * This function is used to derive new, cryptographically separate keys from a
35 * given key in TLS. This PRF is defined in RFC 2246, Chapter 5.
37 int tls_prf(const u8
*secret
, size_t secret_len
, const char *label
,
38 const u8
*seed
, size_t seed_len
, u8
*out
, size_t outlen
)
42 u8 A_MD5
[MD5_MAC_LEN
], A_SHA1
[SHA1_MAC_LEN
];
43 u8 P_MD5
[MD5_MAC_LEN
], P_SHA1
[SHA1_MAC_LEN
];
44 int MD5_pos
, SHA1_pos
;
45 const u8
*MD5_addr
[3];
47 const unsigned char *SHA1_addr
[3];
54 MD5_len
[0] = MD5_MAC_LEN
;
55 MD5_addr
[1] = (unsigned char *) label
;
56 MD5_len
[1] = os_strlen(label
);
58 MD5_len
[2] = seed_len
;
60 SHA1_addr
[0] = A_SHA1
;
61 SHA1_len
[0] = SHA1_MAC_LEN
;
62 SHA1_addr
[1] = (unsigned char *) label
;
63 SHA1_len
[1] = os_strlen(label
);
65 SHA1_len
[2] = seed_len
;
67 /* RFC 2246, Chapter 5
68 * A(0) = seed, A(i) = HMAC(secret, A(i-1))
69 * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + ..
70 * PRF = P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed)
73 L_S1
= L_S2
= (secret_len
+ 1) / 2;
77 /* The last byte of S1 will be shared with S2 */
81 hmac_md5_vector_non_fips_allow(S1
, L_S1
, 2, &MD5_addr
[1], &MD5_len
[1],
83 hmac_sha1_vector(S2
, L_S2
, 2, &SHA1_addr
[1], &SHA1_len
[1], A_SHA1
);
85 MD5_pos
= MD5_MAC_LEN
;
86 SHA1_pos
= SHA1_MAC_LEN
;
87 for (i
= 0; i
< outlen
; i
++) {
88 if (MD5_pos
== MD5_MAC_LEN
) {
89 hmac_md5_vector_non_fips_allow(S1
, L_S1
, 3, MD5_addr
,
92 hmac_md5_non_fips_allow(S1
, L_S1
, A_MD5
, MD5_MAC_LEN
,
95 if (SHA1_pos
== SHA1_MAC_LEN
) {
96 hmac_sha1_vector(S2
, L_S2
, 3, SHA1_addr
, SHA1_len
,
99 hmac_sha1(S2
, L_S2
, A_SHA1
, SHA1_MAC_LEN
, A_SHA1
);
102 out
[i
] = P_MD5
[MD5_pos
] ^ P_SHA1
[SHA1_pos
];