Dmitry Shmidt | 1f69aa5 | 2012-01-24 16:10:04 -0800 | [diff] [blame] | 1 | /* |
| 2 | * TLS PRF P_SHA256 |
| 3 | * Copyright (c) 2011, Jouni Malinen <j@w1.fi> |
| 4 | * |
| 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. |
| 8 | * |
| 9 | * Alternatively, this software may be distributed under the terms of BSD |
| 10 | * license. |
| 11 | * |
| 12 | * See README and COPYING for more details. |
| 13 | */ |
| 14 | |
| 15 | #include "includes.h" |
| 16 | |
| 17 | #include "common.h" |
| 18 | #include "sha256.h" |
| 19 | |
| 20 | |
| 21 | /** |
| 22 | * tls_prf_sha256 - Pseudo-Random Function for TLS v1.2 (P_SHA256, RFC 5246) |
| 23 | * @secret: Key for PRF |
| 24 | * @secret_len: Length of the key in bytes |
| 25 | * @label: A unique label for each purpose of the PRF |
| 26 | * @seed: Seed value to bind into the key |
| 27 | * @seed_len: Length of the seed |
| 28 | * @out: Buffer for the generated pseudo-random key |
| 29 | * @outlen: Number of bytes of key to generate |
| 30 | * Returns: 0 on success, -1 on failure. |
| 31 | * |
| 32 | * This function is used to derive new, cryptographically separate keys from a |
| 33 | * given key in TLS. This PRF is defined in RFC 2246, Chapter 5. |
| 34 | */ |
| 35 | void tls_prf_sha256(const u8 *secret, size_t secret_len, const char *label, |
| 36 | const u8 *seed, size_t seed_len, u8 *out, size_t outlen) |
| 37 | { |
| 38 | size_t clen; |
| 39 | u8 A[SHA256_MAC_LEN]; |
| 40 | u8 P[SHA256_MAC_LEN]; |
| 41 | size_t pos; |
| 42 | const unsigned char *addr[3]; |
| 43 | size_t len[3]; |
| 44 | |
| 45 | addr[0] = A; |
| 46 | len[0] = SHA256_MAC_LEN; |
| 47 | addr[1] = (unsigned char *) label; |
| 48 | len[1] = os_strlen(label); |
| 49 | addr[2] = seed; |
| 50 | len[2] = seed_len; |
| 51 | |
| 52 | /* |
| 53 | * RFC 5246, Chapter 5 |
| 54 | * A(0) = seed, A(i) = HMAC(secret, A(i-1)) |
| 55 | * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + .. |
| 56 | * PRF(secret, label, seed) = P_SHA256(secret, label + seed) |
| 57 | */ |
| 58 | |
| 59 | hmac_sha256_vector(secret, secret_len, 2, &addr[1], &len[1], A); |
| 60 | |
| 61 | pos = 0; |
| 62 | while (pos < outlen) { |
| 63 | hmac_sha256_vector(secret, secret_len, 3, addr, len, P); |
| 64 | hmac_sha256(secret, secret_len, A, SHA256_MAC_LEN, A); |
| 65 | |
| 66 | clen = outlen - pos; |
| 67 | if (clen > SHA256_MAC_LEN) |
| 68 | clen = SHA256_MAC_LEN; |
| 69 | os_memcpy(out + pos, P, clen); |
| 70 | pos += clen; |
| 71 | } |
| 72 | } |