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 
15 #ifdef LTC_ECC_SHAMIR
16 
17 /**
18   @file ecc_recover_key.c
19   ECC Crypto, Russ Williams
20 */
21 
22 /**
23    Recover ECC public key from signature and hash
24    @param sig         The signature to verify
25    @param siglen      The length of the signature (octets)
26    @param hash        The hash (message digest) that was signed
27    @param hashlen     The length of the hash (octets)
28    @param recid       The recovery ID ("v"), can be -1 if signature contains it
29    @param sigformat   The format of the signature (ecc_signature_type)
30    @param key         The recovered public ECC key
31    @return CRYPT_OK if successful (even if the signature is not valid)
32 */
ecc_recover_key(const unsigned char * sig,unsigned long siglen,const unsigned char * hash,unsigned long hashlen,int recid,ecc_signature_type sigformat,ecc_key * key)33 int ecc_recover_key(const unsigned char *sig,  unsigned long siglen,
34                     const unsigned char *hash, unsigned long hashlen,
35                     int recid, ecc_signature_type sigformat, ecc_key *key)
36 {
37    ecc_point     *mG = NULL, *mQ = NULL, *mR = NULL;
38    void          *p, *m, *a, *b;
39    void          *r, *s, *v, *w, *t1, *t2, *u1, *u2, *v1, *v2, *e, *x, *y, *a_plus3;
40    void          *mu = NULL, *ma = NULL;
41    void          *mp = NULL;
42    int           err;
43    unsigned long pbits, pbytes, i, shift_right;
44    unsigned char ch, buf[MAXBLOCKSIZE];
45 
46    LTC_ARGCHK(sig  != NULL);
47    LTC_ARGCHK(hash != NULL);
48    LTC_ARGCHK(key  != NULL);
49 
50    /* BEWARE: requires sqrtmod_prime */
51    if (ltc_mp.sqrtmod_prime == NULL) {
52       return CRYPT_ERROR;
53    }
54 
55    /* allocate ints */
56    if ((err = mp_init_multi(&r, &s, &v, &w, &t1, &t2, &u1, &u2, &v1, &v2, &e, &x, &y, &a_plus3, NULL)) != CRYPT_OK) {
57       return err;
58    }
59 
60    p = key->dp.order;
61    m = key->dp.prime;
62    a = key->dp.A;
63    b = key->dp.B;
64    if ((err = mp_add_d(a, 3, a_plus3)) != CRYPT_OK) {
65       goto error;
66    }
67 
68    /* allocate points */
69    mG = ltc_ecc_new_point();
70    mQ = ltc_ecc_new_point();
71    mR = ltc_ecc_new_point();
72    if (mR == NULL || mQ  == NULL || mG == NULL) {
73       err = CRYPT_MEM;
74       goto error;
75    }
76 
77    if (sigformat == LTC_ECCSIG_ANSIX962) {
78       /* ANSI X9.62 format - ASN.1 encoded SEQUENCE{ INTEGER(r), INTEGER(s) }  */
79       if ((err = der_decode_sequence_multi_ex(sig, siglen, LTC_DER_SEQ_SEQUENCE | LTC_DER_SEQ_STRICT,
80                                      LTC_ASN1_INTEGER, 1UL, r,
81                                      LTC_ASN1_INTEGER, 1UL, s,
82                                      LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK)                             { goto error; }
83    }
84    else if (sigformat == LTC_ECCSIG_RFC7518) {
85       /* RFC7518 format - raw (r,s) */
86       i = mp_unsigned_bin_size(key->dp.order);
87       if (siglen != (2*i)) {
88          err = CRYPT_INVALID_PACKET;
89          goto error;
90       }
91       if ((err = mp_read_unsigned_bin(r, (unsigned char *)sig,   i)) != CRYPT_OK)                       { goto error; }
92       if ((err = mp_read_unsigned_bin(s, (unsigned char *)sig+i, i)) != CRYPT_OK)                       { goto error; }
93    }
94    else if (sigformat == LTC_ECCSIG_ETH27) {
95       /* Ethereum (v,r,s) format */
96       if (pk_oid_cmp_with_ulong("1.3.132.0.10", key->dp.oid, key->dp.oidlen) != CRYPT_OK) {
97          /* Only valid for secp256k1 - OID 1.3.132.0.10 */
98          err = CRYPT_ERROR; goto error;
99       }
100       if (siglen != 65) { /* Only secp256k1 curves use this format, so must be 65 bytes long */
101          err = CRYPT_INVALID_PACKET;
102          goto error;
103       }
104       i = (unsigned long)sig[64];
105       if ((i>=27) && (i<31)) i -= 27; /* Ethereum adds 27 to recovery ID */
106       if (recid >= 0 && ((unsigned long)recid != i)) {
107          /* Recovery ID specified, but doesn't match signature */
108          err = CRYPT_INVALID_PACKET;
109          goto error;
110       }
111       recid = i;
112       if ((err = mp_read_unsigned_bin(r, (unsigned char *)sig,  32)) != CRYPT_OK)                       { goto error; }
113       if ((err = mp_read_unsigned_bin(s, (unsigned char *)sig+32, 32)) != CRYPT_OK)                     { goto error; }
114    }
115 #ifdef LTC_SSH
116    else if (sigformat == LTC_ECCSIG_RFC5656) {
117       char name[64], name2[64];
118       unsigned long namelen = sizeof(name2);
119 
120       /* Decode as SSH data sequence, per RFC4251 */
121       if ((err = ssh_decode_sequence_multi(sig, siglen,
122                                            LTC_SSHDATA_STRING, name, 64,
123                                            LTC_SSHDATA_MPINT,  r,
124                                            LTC_SSHDATA_MPINT,  s,
125                                            LTC_SSHDATA_EOL,    NULL)) != CRYPT_OK)                      { goto error; }
126 
127 
128       /* Check curve matches identifier string */
129       if ((err = ecc_ssh_ecdsa_encode_name(name2, &namelen, key)) != CRYPT_OK)                                { goto error; }
130       if (XSTRCMP(name,name2) != 0) {
131          err = CRYPT_INVALID_ARG;
132          goto error;
133       }
134    }
135 #endif
136    else {
137       /* Unknown signature format */
138       err = CRYPT_ERROR;
139       goto error;
140    }
141 
142    if (recid < 0 || (unsigned long)recid >= 2*(key->dp.cofactor+1)) {
143       /* Recovery ID is out of range, reject it */
144       err = CRYPT_INVALID_ARG;
145       goto error;
146    }
147 
148    /* check for zero */
149    if (mp_cmp_d(r, 0) != LTC_MP_GT || mp_cmp_d(s, 0) != LTC_MP_GT ||
150        mp_cmp(r, p) != LTC_MP_LT || mp_cmp(s, p) != LTC_MP_LT) {
151       err = CRYPT_INVALID_PACKET;
152       goto error;
153    }
154 
155    /* read hash - truncate if needed */
156    pbits = mp_count_bits(p);
157    pbytes = (pbits+7) >> 3;
158    if (pbits > hashlen*8) {
159       if ((err = mp_read_unsigned_bin(e, (unsigned char *)hash, hashlen)) != CRYPT_OK)                  { goto error; }
160    }
161    else if (pbits % 8 == 0) {
162       if ((err = mp_read_unsigned_bin(e, (unsigned char *)hash, pbytes)) != CRYPT_OK)                   { goto error; }
163    }
164    else {
165       shift_right = 8 - pbits % 8;
166       for (i=0, ch=0; i<pbytes; i++) {
167         buf[i] = ch;
168         ch = (hash[i] << (8-shift_right));
169         buf[i] = buf[i] ^ (hash[i] >> shift_right);
170       }
171       if ((err = mp_read_unsigned_bin(e, (unsigned char *)buf, pbytes)) != CRYPT_OK)                    { goto error; }
172    }
173 
174    /* decompress point from r=(x mod p) - BEWARE: requires sqrtmod_prime */
175    /* x = r + p*(recid/2) */
176    if ((err = mp_set(x, recid/2)) != CRYPT_OK)                                                          { goto error; }
177    if ((err = mp_mulmod(p, x, m, x)) != CRYPT_OK)                                                       { goto error; }
178    if ((err = mp_add(x, r, x)) != CRYPT_OK)                                                             { goto error; }
179    /* compute x^3 */
180    if ((err = mp_sqr(x, t1)) != CRYPT_OK)                                                               { goto error; }
181    if ((err = mp_mulmod(t1, x, m, t1)) != CRYPT_OK)                                                     { goto error; }
182    /* compute x^3 + a*x */
183    if ((err = mp_mulmod(a, x, m, t2)) != CRYPT_OK)                                                      { goto error; }
184    if ((err = mp_add(t1, t2, t1)) != CRYPT_OK)                                                          { goto error; }
185    /* compute x^3 + a*x + b */
186    if ((err = mp_add(t1, b, t1)) != CRYPT_OK)                                                           { goto error; }
187    /* compute sqrt(x^3 + a*x + b) */
188    if ((err = mp_sqrtmod_prime(t1, m, t2)) != CRYPT_OK)                                                 { goto error; }
189 
190    /* fill in mR */
191    if ((err = mp_copy(x, mR->x)) != CRYPT_OK)                                                           { goto error; }
192    if ((mp_isodd(t2) && (recid%2)) || (!mp_isodd(t2) && !(recid%2))) {
193       if ((err = mp_mod(t2, m, mR->y)) != CRYPT_OK)                                                     { goto error; }
194    }
195    else {
196       if ((err = mp_submod(m, t2, m, mR->y)) != CRYPT_OK)                                               { goto error; }
197    }
198    if ((err = mp_set(mR->z, 1)) != CRYPT_OK)                                                            { goto error; }
199 
200    /*  w  = r^-1 mod n */
201    if ((err = mp_invmod(r, p, w)) != CRYPT_OK)                                                          { goto error; }
202    /* v1 = sw */
203    if ((err = mp_mulmod(s, w, p, v1)) != CRYPT_OK)                                                      { goto error; }
204    /* v2 = -ew */
205    if ((err = mp_mulmod(e, w, p, v2)) != CRYPT_OK)                                                      { goto error; }
206    if ((err = mp_submod(p, v2, p, v2)) != CRYPT_OK)                                                     { goto error; }
207 
208    /*  w  = s^-1 mod n */
209    if ((err = mp_invmod(s, p, w)) != CRYPT_OK)                                                          { goto error; }
210    /* u1 = ew */
211    if ((err = mp_mulmod(e, w, p, u1)) != CRYPT_OK)                                                      { goto error; }
212    /* u2 = rw */
213    if ((err = mp_mulmod(r, w, p, u2)) != CRYPT_OK)                                                      { goto error; }
214 
215    /* find mG */
216    if ((err = ltc_ecc_copy_point(&key->dp.base, mG)) != CRYPT_OK)                                       { goto error; }
217 
218    /* find the montgomery mp */
219    if ((err = mp_montgomery_setup(m, &mp)) != CRYPT_OK)                                                 { goto error; }
220 
221    /* for curves with a == -3 keep ma == NULL */
222    if (mp_cmp(a_plus3, m) != LTC_MP_EQ) {
223       if ((err = mp_init_multi(&mu, &ma, NULL)) != CRYPT_OK)                                            { goto error; }
224       if ((err = mp_montgomery_normalization(mu, m)) != CRYPT_OK)                                       { goto error; }
225       if ((err = mp_mulmod(a, mu, m, ma)) != CRYPT_OK)                                                  { goto error; }
226    }
227 
228    /* recover mQ from mR */
229    /* compute v1*mR + v2*mG = mQ using Shamir's trick */
230    if ((err = ltc_mp.ecc_mul2add(mR, v1, mG, v2, mQ, ma, m)) != CRYPT_OK)                               { goto error; }
231 
232    /* compute u1*mG + u2*mQ = mG using Shamir's trick */
233    if ((err = ltc_mp.ecc_mul2add(mG, u1, mQ, u2, mG, ma, m)) != CRYPT_OK)                               { goto error; }
234 
235    /* v = X_x1 mod n */
236    if ((err = mp_mod(mG->x, p, v)) != CRYPT_OK)                                                         { goto error; }
237 
238    /* does v == r */
239    if (mp_cmp(v, r) == LTC_MP_EQ) {
240       /* found public key which verifies signature */
241       if ((err = ltc_ecc_copy_point(mQ, &key->pubkey)) != CRYPT_OK)                                     { goto error; }
242       /* point on the curve + other checks */
243       if ((err = ltc_ecc_verify_key(key)) != CRYPT_OK)                                                  { goto error; }
244 
245       key->type = PK_PUBLIC;
246 
247       err = CRYPT_OK;
248    }
249    else {
250       /* not found - recid is wrong or we're unable to calculate public key for some other reason */
251       err = CRYPT_INVALID_ARG;
252    }
253 
254 error:
255    if (ma != NULL) mp_clear(ma);
256    if (mu != NULL) mp_clear(mu);
257    if (mp != NULL) mp_montgomery_free(mp);
258    if (mR != NULL) ltc_ecc_del_point(mR);
259    if (mQ != NULL) ltc_ecc_del_point(mQ);
260    if (mG != NULL) ltc_ecc_del_point(mG);
261    mp_clear_multi(a_plus3, y, x, e, v2, v1, u2, u1, t2, t1, w, v, s, r, NULL);
262    return err;
263 }
264 
265 #endif
266 #endif
267 
268 /* ref:         $Format:%D$ */
269 /* git commit:  $Format:%H$ */
270 /* commit time: $Format:%ai$ */
271