xref: /optee_os/core/lib/libtomcrypt/dh.c (revision 12484fc76d224d174b691b211fff84265077ff1b)
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.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;
43 	dh_key ltc_tmp_key;
44 	int ltc_res;
45 
46 	/* Generate the DH key */
47 	ltc_tmp_key.g = key->g;
48 	ltc_tmp_key.p = key->p;
49 	ltc_res = dh_make_key(NULL, find_prng("prng_crypto"), q, xbits,
50 			      &ltc_tmp_key);
51 	if (ltc_res != CRYPT_OK) {
52 		res = TEE_ERROR_BAD_PARAMETERS;
53 	} else {
54 		ltc_mp.copy(ltc_tmp_key.y,  key->y);
55 		ltc_mp.copy(ltc_tmp_key.x,  key->x);
56 
57 		/* Free the tempory key */
58 		dh_free(&ltc_tmp_key);
59 		res = TEE_SUCCESS;
60 	}
61 	return res;
62 }
63 
64 TEE_Result crypto_acipher_dh_shared_secret(struct dh_keypair *private_key,
65 					   struct bignum *public_key,
66 					   struct bignum *secret)
67 {
68 	int err;
69 	dh_key pk = {
70 		.type = PK_PRIVATE,
71 		.g = private_key->g,
72 		.p = private_key->p,
73 		.y = private_key->y,
74 		.x = private_key->x
75 	};
76 
77 	err = dh_shared_secret(&pk, public_key, secret);
78 	return ((err == CRYPT_OK) ? TEE_SUCCESS : TEE_ERROR_BAD_PARAMETERS);
79 }
80