xref: /freebsd/contrib/wpa/src/crypto/crypto_internal-modexp.c (revision da5069e1f7daaef1e7157876d6044de6f3a08ce2)
1 /*
2  * Crypto wrapper for internal crypto implementation - modexp
3  * Copyright (c) 2006-2009, 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 
11 #include "common.h"
12 #include "tls/bignum.h"
13 #include "crypto.h"
14 
15 
16 int crypto_dh_init(u8 generator, const u8 *prime, size_t prime_len, u8 *privkey,
17 		   u8 *pubkey)
18 {
19 	size_t pubkey_len, pad;
20 
21 	if (os_get_random(privkey, prime_len) < 0)
22 		return -1;
23 	if (os_memcmp(privkey, prime, prime_len) > 0) {
24 		/* Make sure private value is smaller than prime */
25 		privkey[0] = 0;
26 	}
27 
28 	pubkey_len = prime_len;
29 	if (crypto_mod_exp(&generator, 1, privkey, prime_len, prime, prime_len,
30 			   pubkey, &pubkey_len) < 0)
31 		return -1;
32 	if (pubkey_len < prime_len) {
33 		pad = prime_len - pubkey_len;
34 		os_memmove(pubkey + pad, pubkey, pubkey_len);
35 		os_memset(pubkey, 0, pad);
36 	}
37 
38 	return 0;
39 }
40 
41 
42 int crypto_dh_derive_secret(u8 generator, const u8 *prime, size_t prime_len,
43 			    const u8 *privkey, size_t privkey_len,
44 			    const u8 *pubkey, size_t pubkey_len,
45 			    u8 *secret, size_t *len)
46 {
47 	return crypto_mod_exp(pubkey, pubkey_len, privkey, privkey_len,
48 			      prime, prime_len, secret, len);
49 }
50 
51 
52 int crypto_mod_exp(const u8 *base, size_t base_len,
53 		   const u8 *power, size_t power_len,
54 		   const u8 *modulus, size_t modulus_len,
55 		   u8 *result, size_t *result_len)
56 {
57 	struct bignum *bn_base, *bn_exp, *bn_modulus, *bn_result;
58 	int ret = -1;
59 
60 	bn_base = bignum_init();
61 	bn_exp = bignum_init();
62 	bn_modulus = bignum_init();
63 	bn_result = bignum_init();
64 
65 	if (bn_base == NULL || bn_exp == NULL || bn_modulus == NULL ||
66 	    bn_result == NULL)
67 		goto error;
68 
69 	if (bignum_set_unsigned_bin(bn_base, base, base_len) < 0 ||
70 	    bignum_set_unsigned_bin(bn_exp, power, power_len) < 0 ||
71 	    bignum_set_unsigned_bin(bn_modulus, modulus, modulus_len) < 0)
72 		goto error;
73 
74 	if (bignum_exptmod(bn_base, bn_exp, bn_modulus, bn_result) < 0)
75 		goto error;
76 
77 	ret = bignum_get_unsigned_bin(bn_result, result, result_len);
78 
79 error:
80 	bignum_deinit(bn_base);
81 	bignum_deinit(bn_exp);
82 	bignum_deinit(bn_modulus);
83 	bignum_deinit(bn_result);
84 	return ret;
85 }
86