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