xref: /optee_os/core/lib/libtomcrypt/dh.c (revision 5b25c76ac40f830867e3d60800120ffd7874e8dc)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014-2019, Linaro Limited
4  */
5 
6 #include <crypto/crypto.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <tee_api_types.h>
10 #include <trace.h>
11 #include <utee_defines.h>
12 
13 #include "acipher_helpers.h"
14 
15 TEE_Result crypto_acipher_alloc_dh_keypair(struct dh_keypair *s,
16 					   size_t key_size_bits __unused)
17 {
18 	memset(s, 0, sizeof(*s));
19 	if (!bn_alloc_max(&s->g))
20 		return TEE_ERROR_OUT_OF_MEMORY;
21 	if (!bn_alloc_max(&s->p))
22 		goto err;
23 	if (!bn_alloc_max(&s->y))
24 		goto err;
25 	if (!bn_alloc_max(&s->x))
26 		goto err;
27 	if (!bn_alloc_max(&s->q))
28 		goto err;
29 	return TEE_SUCCESS;
30 err:
31 	crypto_bignum_free(s->g);
32 	crypto_bignum_free(s->p);
33 	crypto_bignum_free(s->y);
34 	crypto_bignum_free(s->x);
35 	return TEE_ERROR_OUT_OF_MEMORY;
36 }
37 
38 TEE_Result crypto_acipher_gen_dh_key(struct dh_keypair *key, struct bignum *q,
39 				     size_t xbits)
40 {
41 	TEE_Result res = TEE_ERROR_GENERIC;
42 	dh_key ltc_tmp_key = { };
43 	int ltc_res = 0;
44 
45 	ltc_res = mp_init_multi(&ltc_tmp_key.base, &ltc_tmp_key.prime, NULL);
46 	if (ltc_res != CRYPT_OK)
47 		return TEE_ERROR_OUT_OF_MEMORY;
48 
49 	/* Generate the DH key */
50 	mp_copy(key->g, ltc_tmp_key.base);
51 	mp_copy(key->p, ltc_tmp_key.prime);
52 	ltc_res = dh_make_key(NULL, find_prng("prng_crypto"), q, xbits,
53 			      &ltc_tmp_key);
54 	if (ltc_res != CRYPT_OK) {
55 		res = TEE_ERROR_BAD_PARAMETERS;
56 	} else {
57 		ltc_mp.copy(ltc_tmp_key.y,  key->y);
58 		ltc_mp.copy(ltc_tmp_key.x,  key->x);
59 		res = TEE_SUCCESS;
60 	}
61 
62 	dh_free(&ltc_tmp_key);
63 	return res;
64 }
65 
66 TEE_Result crypto_acipher_dh_shared_secret(struct dh_keypair *private_key,
67 					   struct bignum *public_key,
68 					   struct bignum *secret)
69 {
70 	int err;
71 
72 	if (!private_key || !public_key || !secret)
73 		return TEE_ERROR_BAD_PARAMETERS;
74 
75 	err = mp_exptmod(public_key, private_key->x, private_key->p, secret);
76 	return ((err == CRYPT_OK) ? TEE_SUCCESS : TEE_ERROR_BAD_PARAMETERS);
77 
78 }
79