xref: /freebsd/contrib/wpa/src/crypto/fips_prf_openssl.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /*
2  * FIPS 186-2 PRF for libcrypto
3  * Copyright (c) 2004-2005, 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 #include <openssl/sha.h>
11 
12 #include "common.h"
13 #include "crypto.h"
14 
15 
16 static void sha1_transform(u32 *state, const u8 data[64])
17 {
18 	SHA_CTX context;
19 	os_memset(&context, 0, sizeof(context));
20 	context.h0 = state[0];
21 	context.h1 = state[1];
22 	context.h2 = state[2];
23 	context.h3 = state[3];
24 	context.h4 = state[4];
25 	SHA1_Transform(&context, data);
26 	state[0] = context.h0;
27 	state[1] = context.h1;
28 	state[2] = context.h2;
29 	state[3] = context.h3;
30 	state[4] = context.h4;
31 }
32 
33 
34 int fips186_2_prf(const u8 *seed, size_t seed_len, u8 *x, size_t xlen)
35 {
36 	u8 xkey[64];
37 	u32 t[5], _t[5];
38 	int i, j, m, k;
39 	u8 *xpos = x;
40 	u32 carry;
41 
42 	if (seed_len < sizeof(xkey))
43 		os_memset(xkey + seed_len, 0, sizeof(xkey) - seed_len);
44 	else
45 		seed_len = sizeof(xkey);
46 
47 	/* FIPS 186-2 + change notice 1 */
48 
49 	os_memcpy(xkey, seed, seed_len);
50 	t[0] = 0x67452301;
51 	t[1] = 0xEFCDAB89;
52 	t[2] = 0x98BADCFE;
53 	t[3] = 0x10325476;
54 	t[4] = 0xC3D2E1F0;
55 
56 	m = xlen / 40;
57 	for (j = 0; j < m; j++) {
58 		/* XSEED_j = 0 */
59 		for (i = 0; i < 2; i++) {
60 			/* XVAL = (XKEY + XSEED_j) mod 2^b */
61 
62 			/* w_i = G(t, XVAL) */
63 			os_memcpy(_t, t, 20);
64 			sha1_transform(_t, xkey);
65 			_t[0] = host_to_be32(_t[0]);
66 			_t[1] = host_to_be32(_t[1]);
67 			_t[2] = host_to_be32(_t[2]);
68 			_t[3] = host_to_be32(_t[3]);
69 			_t[4] = host_to_be32(_t[4]);
70 			os_memcpy(xpos, _t, 20);
71 
72 			/* XKEY = (1 + XKEY + w_i) mod 2^b */
73 			carry = 1;
74 			for (k = 19; k >= 0; k--) {
75 				carry += xkey[k] + xpos[k];
76 				xkey[k] = carry & 0xff;
77 				carry >>= 8;
78 			}
79 
80 			xpos += 20;
81 		}
82 		/* x_j = w_0|w_1 */
83 	}
84 
85 	return 0;
86 }
87