1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10
11 #include "tomcrypt_private.h"
12
13 /**
14 @file ecc_make_key.c
15 ECC Crypto, Tom St Denis
16 */
17
18 #ifdef LTC_MECC
19
20 /**
21 Make a new ECC key
22 @param prng An active PRNG state
23 @param wprng The index of the PRNG you wish to use
24 @param keysize The keysize for the new key (in octets from 20 to 65 bytes)
25 @param key [out] Destination of the newly created key
26 @return CRYPT_OK if successful, upon error all allocated memory will be freed
27 */
ecc_make_key(prng_state * prng,int wprng,int keysize,ecc_key * key)28 int ecc_make_key(prng_state *prng, int wprng, int keysize, ecc_key *key)
29 {
30 int err;
31
32 if ((err = ecc_set_curve_by_size(keysize, key)) != CRYPT_OK) { return err; }
33 if ((err = ecc_generate_key(prng, wprng, key)) != CRYPT_OK) { return err; }
34 return CRYPT_OK;
35 }
36
ecc_make_key_ex(prng_state * prng,int wprng,ecc_key * key,const ltc_ecc_curve * cu)37 int ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_curve *cu)
38 {
39 int err;
40 if ((err = ecc_set_curve(cu, key)) != CRYPT_OK) { return err; }
41 if ((err = ecc_generate_key(prng, wprng, key)) != CRYPT_OK) { return err; }
42 return CRYPT_OK;
43 }
44
ecc_generate_key(prng_state * prng,int wprng,ecc_key * key)45 int ecc_generate_key(prng_state *prng, int wprng, ecc_key *key)
46 {
47 int err;
48
49 LTC_ARGCHK(ltc_mp.name != NULL);
50 LTC_ARGCHK(key != NULL);
51 LTC_ARGCHK(key->dp.size > 0);
52
53 /* ECC key pair generation according to FIPS-186-4 (B.4.2 Key Pair Generation by Testing Candidates):
54 * the generated private key k should be the range [1, order-1]
55 * a/ N = bitlen(order)
56 * b/ generate N random bits and convert them into big integer k
57 * c/ if k not in [1, order-1] go to b/
58 * e/ Q = k*G
59 */
60 if ((err = rand_bn_upto(key->k, key->dp.order, prng, wprng)) != CRYPT_OK) {
61 goto error;
62 }
63
64 /* make the public key */
65 if ((err = ltc_mp.ecc_ptmul(key->k, &key->dp.base, &key->pubkey, key->dp.A, key->dp.prime, 1)) != CRYPT_OK) {
66 goto error;
67 }
68 key->type = PK_PRIVATE;
69
70 /* success */
71 err = CRYPT_OK;
72 goto cleanup;
73
74 error:
75 ecc_free(key);
76 cleanup:
77 return err;
78 }
79
80 #endif
81 /* ref: $Format:%D$ */
82 /* git commit: $Format:%H$ */
83 /* commit time: $Format:%ai$ */
84
85