Fix whitespace.
[tinc] / src / openssl / prf.c
1 /*
2     prf.c -- Pseudo-Random Function for key material generation
3     Copyright (C) 2011 Guus Sliepen <guus@tinc-vpn.org>
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 as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
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.
14
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.
18 */
19
20 #include "system.h"
21
22 #include <openssl/obj_mac.h>
23
24 #include "digest.h"
25 #include "prf.h"
26
27 /* Generate key material from a master secret and a seed, based on RFC 4346 section 5.
28    We use SHA512 instead of MD5 and SHA1.
29  */
30
31 static bool prf_xor(int nid, const char *secret, size_t secretlen, char *seed, size_t seedlen, char *out, ssize_t outlen) {
32         digest_t digest;
33
34         if(!digest_open_by_nid(&digest, nid, -1))
35                 return false;
36
37         if(!digest_set_key(&digest, secret, secretlen))
38                 return false;
39
40         size_t len = digest_length(&digest);
41
42         /* Data is what the "inner" HMAC function processes.
43            It consists of the previous HMAC result plus the seed.
44          */
45
46         char data[len + seedlen];
47         memset(data, 0, len);
48         memcpy(data + len, seed, seedlen);
49
50         char hash[len];
51
52         while(outlen > 0) {
53                 /* Inner HMAC */
54                 digest_create(&digest, data, len + seedlen, data);
55
56                 /* Outer HMAC */
57                 digest_create(&digest, data, len + seedlen, hash);
58
59                 /* XOR the results of the outer HMAC into the out buffer */
60                 for(int i = 0; i < len && i < outlen; i++)
61                         *out++ ^= hash[i];
62
63                 outlen -= len;
64         }
65
66         digest_close(&digest);
67         return true;
68 }
69
70 bool prf(const char *secret, size_t secretlen, char *seed, size_t seedlen, char *out, size_t outlen) {
71         /* This construction allows us to easily switch back to a scheme where the PRF is calculated using two different digest algorithms. */
72         memset(out, 0, outlen);
73
74         return prf_xor(NID_sha512, secret, secretlen, seed, seedlen, out, outlen);
75 }