1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_MECC
7 
ecc_set_curve(const ltc_ecc_curve * cu,ecc_key * key)8 int ecc_set_curve(const ltc_ecc_curve *cu, ecc_key *key)
9 {
10    int err;
11 
12    LTC_ARGCHK(key != NULL);
13    LTC_ARGCHK(cu != NULL);
14 
15    if ((err = mp_init_multi(&key->dp.prime, &key->dp.order, &key->dp.A, &key->dp.B,
16                             &key->dp.base.x, &key->dp.base.y, &key->dp.base.z,
17                             &key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
18                             NULL)) != CRYPT_OK) {
19       return err;
20    }
21 
22    /* A, B, order, prime, Gx, Gy */
23    if ((err = mp_read_radix(key->dp.prime, cu->prime, 16)) != CRYPT_OK) { goto error; }
24    if ((err = mp_read_radix(key->dp.order, cu->order, 16)) != CRYPT_OK) { goto error; }
25    if ((err = mp_read_radix(key->dp.A, cu->A, 16)) != CRYPT_OK)         { goto error; }
26    if ((err = mp_read_radix(key->dp.B, cu->B, 16)) != CRYPT_OK)         { goto error; }
27    if ((err = mp_read_radix(key->dp.base.x, cu->Gx, 16)) != CRYPT_OK)   { goto error; }
28    if ((err = mp_read_radix(key->dp.base.y, cu->Gy, 16)) != CRYPT_OK)   { goto error; }
29    if ((err = mp_set(key->dp.base.z, 1)) != CRYPT_OK)                   { goto error; }
30    /* cofactor & size */
31    key->dp.cofactor = cu->cofactor;
32    key->dp.size = mp_unsigned_bin_size(key->dp.prime);
33    /* OID string >> unsigned long oid[16] + oidlen */
34    key->dp.oidlen = 16;
35    if ((err = pk_oid_str_to_num(cu->OID, key->dp.oid, &key->dp.oidlen)) != CRYPT_OK) { goto error; }
36    /* success */
37    return CRYPT_OK;
38 
39 error:
40    ecc_free(key);
41    return err;
42 }
43 
ecc_set_curve_by_size(int size,ecc_key * key)44 int ecc_set_curve_by_size(int size, ecc_key *key)
45 {
46    const ltc_ecc_curve *cu = NULL;
47    int err = CRYPT_ERROR;
48 
49    /* for compatibility with libtomcrypt-1.17 the sizes below must match the specific curves */
50    if (size <= 14) {
51       err = ecc_find_curve("SECP112R1", &cu);
52    }
53    else if (size <= 16) {
54       err = ecc_find_curve("SECP128R1", &cu);
55    }
56    else if (size <= 20) {
57       err = ecc_find_curve("SECP160R1", &cu);
58    }
59    else if (size <= 24) {
60       err = ecc_find_curve("SECP192R1", &cu);
61    }
62    else if (size <= 28) {
63       err = ecc_find_curve("SECP224R1", &cu);
64    }
65    else if (size <= 32) {
66       err = ecc_find_curve("SECP256R1", &cu);
67    }
68    else if (size <= 48) {
69       err = ecc_find_curve("SECP384R1", &cu);
70    }
71    else if (size <= 66) {
72       err = ecc_find_curve("SECP521R1", &cu);
73    }
74 
75    if (err == CRYPT_OK && cu != NULL) return ecc_set_curve(cu, key);
76 
77    return CRYPT_INVALID_ARG;
78 }
79 
80 #endif
81