2 prf.c -- Pseudo-Random Function for key material generation
3 Copyright (C) 2011-2013 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "../system.h"
22 #include <openssl/obj_mac.h>
25 #include "../digest.h"
28 /* Generate key material from a master secret and a seed, based on RFC 4346 section 5.
29 We use SHA512 instead of MD5 and SHA1.
32 static bool prf_xor(int nid, const uint8_t *secret, size_t secretlen, uint8_t *seed, size_t seedlen, uint8_t *out, size_t outlen) {
33 digest_t digest = {0};
35 if(!digest_open_by_nid(&digest, nid, DIGEST_ALGO_SIZE)) {
36 digest_close(&digest);
40 if(!digest_set_key(&digest, secret, secretlen)) {
41 digest_close(&digest);
45 size_t len = digest_length(&digest);
47 /* Data is what the "inner" HMAC function processes.
48 It consists of the previous HMAC result plus the seed.
51 char *data = alloca(len + seedlen);
53 memcpy(data + len, seed, seedlen);
55 uint8_t *hash = alloca(len);
59 if(!digest_create(&digest, data, len + seedlen, data)) {
60 digest_close(&digest);
65 if(!digest_create(&digest, data, len + seedlen, hash)) {
66 digest_close(&digest);
70 /* XOR the results of the outer HMAC into the out buffer */
73 for(i = 0; i < len && i < outlen; i++) {
80 digest_close(&digest);
84 bool prf(const uint8_t *secret, size_t secretlen, uint8_t *seed, size_t seedlen, uint8_t *out, size_t outlen) {
85 /* This construction allows us to easily switch back to a scheme where the PRF is calculated using two different digest algorithms. */
86 memset(out, 0, outlen);
88 return prf_xor(NID_sha512, secret, secretlen, seed, seedlen, out, outlen);