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 
crypto_acipher_alloc_dh_keypair(struct dh_keypair * s,size_t key_size_bits __unused)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 
crypto_acipher_gen_dh_key(struct dh_keypair * key,struct bignum * q,size_t xbits,size_t key_size)38 TEE_Result crypto_acipher_gen_dh_key(struct dh_keypair *key, struct bignum *q,
39 				     size_t xbits, size_t key_size)
40 {
41 	TEE_Result res = TEE_ERROR_GENERIC;
42 	dh_key ltc_tmp_key = { };
43 	int ltc_res = 0;
44 
45 	if (key_size != 8 * mp_unsigned_bin_size(key->p))
46 		return TEE_ERROR_BAD_PARAMETERS;
47 
48 	ltc_res = mp_init_multi(&ltc_tmp_key.base, &ltc_tmp_key.prime, NULL);
49 	if (ltc_res != CRYPT_OK)
50 		return TEE_ERROR_OUT_OF_MEMORY;
51 
52 	/* Generate the DH key */
53 	mp_copy(key->g, ltc_tmp_key.base);
54 	mp_copy(key->p, ltc_tmp_key.prime);
55 	ltc_res = dh_make_key(NULL, find_prng("prng_crypto"), q, xbits,
56 			      &ltc_tmp_key);
57 	if (ltc_res != CRYPT_OK) {
58 		res = TEE_ERROR_BAD_PARAMETERS;
59 	} else {
60 		ltc_mp.copy(ltc_tmp_key.y,  key->y);
61 		ltc_mp.copy(ltc_tmp_key.x,  key->x);
62 		res = TEE_SUCCESS;
63 	}
64 
65 	dh_free(&ltc_tmp_key);
66 	return res;
67 }
68 
crypto_acipher_dh_shared_secret(struct dh_keypair * private_key,struct bignum * public_key,struct bignum * secret)69 TEE_Result crypto_acipher_dh_shared_secret(struct dh_keypair *private_key,
70 					   struct bignum *public_key,
71 					   struct bignum *secret)
72 {
73 	int err;
74 
75 	if (!private_key || !public_key || !secret)
76 		return TEE_ERROR_BAD_PARAMETERS;
77 
78 	err = mp_exptmod(public_key, private_key->x, private_key->p, secret);
79 	return ((err == CRYPT_OK) ? TEE_SUCCESS : TEE_ERROR_BAD_PARAMETERS);
80 
81 }
82