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 #ifdef LTC_MECC
14 
ecc_set_key(const unsigned char * in,unsigned long inlen,int type,ecc_key * key)15 int ecc_set_key(const unsigned char *in, unsigned long inlen, int type, ecc_key *key)
16 {
17    int err;
18    void *prime, *a, *b;
19 
20    LTC_ARGCHK(key != NULL);
21    LTC_ARGCHK(in != NULL);
22    LTC_ARGCHK(inlen > 0);
23 
24    prime = key->dp.prime;
25    a     = key->dp.A;
26    b     = key->dp.B;
27 
28    if (type == PK_PRIVATE) {
29       /* load private key */
30       if ((err = mp_read_unsigned_bin(key->k, (unsigned char *)in, inlen)) != CRYPT_OK) {
31          goto error;
32       }
33       if (mp_iszero(key->k) || (mp_cmp(key->k, key->dp.order) != LTC_MP_LT)) {
34          err = CRYPT_INVALID_PACKET;
35          goto error;
36       }
37       /* compute public key */
38       if ((err = ltc_mp.ecc_ptmul(key->k, &key->dp.base, &key->pubkey, a, prime, 1)) != CRYPT_OK)         { goto error; }
39    }
40    else if (type == PK_PUBLIC) {
41       /* load public key */
42       if ((err = ltc_ecc_import_point(in, inlen, prime, a, b, key->pubkey.x, key->pubkey.y)) != CRYPT_OK) { goto error; }
43       if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK)                                                   { goto error; }
44    }
45    else {
46       err = CRYPT_INVALID_PACKET;
47       goto error;
48    }
49 
50    /* point on the curve + other checks */
51    if ((err = ltc_ecc_verify_key(key)) != CRYPT_OK) {
52       goto error;
53    }
54 
55    key->type = type;
56    return CRYPT_OK;
57 
58 error:
59    ecc_free(key);
60    return err;
61 }
62 
63 #endif
64 
65 /* ref:         $Format:%D$ */
66 /* git commit:  $Format:%H$ */
67 /* commit time: $Format:%ai$ */
68