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