Deprecate EC_KEY + Update ec apps to use EVP_PKEY
[openssl.git] / crypto / sm2 / sm2_sign.c
1 /*
2  * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2017 Ribose Inc. All Rights Reserved.
4  * Ported from Ribose contributions from Botan.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include "internal/deprecated.h"
13
14 #include "crypto/sm2.h"
15 #include "crypto/sm2err.h"
16 #include "crypto/ec.h" /* ec_group_do_inverse_ord() */
17 #include "internal/numbers.h"
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #include <openssl/err.h>
21 #include <openssl/bn.h>
22 #include <string.h>
23
24 int sm2_compute_z_digest(uint8_t *out,
25                          const EVP_MD *digest,
26                          const uint8_t *id,
27                          const size_t id_len,
28                          const EC_KEY *key)
29 {
30     int rc = 0;
31     const EC_GROUP *group = EC_KEY_get0_group(key);
32     BN_CTX *ctx = NULL;
33     EVP_MD_CTX *hash = NULL;
34     BIGNUM *p = NULL;
35     BIGNUM *a = NULL;
36     BIGNUM *b = NULL;
37     BIGNUM *xG = NULL;
38     BIGNUM *yG = NULL;
39     BIGNUM *xA = NULL;
40     BIGNUM *yA = NULL;
41     int p_bytes = 0;
42     uint8_t *buf = NULL;
43     uint16_t entl = 0;
44     uint8_t e_byte = 0;
45
46     hash = EVP_MD_CTX_new();
47     ctx = BN_CTX_new_ex(ec_key_get_libctx(key));
48     if (hash == NULL || ctx == NULL) {
49         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
50         goto done;
51     }
52
53     p = BN_CTX_get(ctx);
54     a = BN_CTX_get(ctx);
55     b = BN_CTX_get(ctx);
56     xG = BN_CTX_get(ctx);
57     yG = BN_CTX_get(ctx);
58     xA = BN_CTX_get(ctx);
59     yA = BN_CTX_get(ctx);
60
61     if (yA == NULL) {
62         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
63         goto done;
64     }
65
66     if (!EVP_DigestInit(hash, digest)) {
67         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
68         goto done;
69     }
70
71     /* Z = h(ENTL || ID || a || b || xG || yG || xA || yA) */
72
73     if (id_len >= (UINT16_MAX / 8)) {
74         /* too large */
75         ERR_raise(ERR_LIB_SM2, SM2_R_ID_TOO_LARGE);
76         goto done;
77     }
78
79     entl = (uint16_t)(8 * id_len);
80
81     e_byte = entl >> 8;
82     if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
83         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
84         goto done;
85     }
86     e_byte = entl & 0xFF;
87     if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
88         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
89         goto done;
90     }
91
92     if (id_len > 0 && !EVP_DigestUpdate(hash, id, id_len)) {
93         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
94         goto done;
95     }
96
97     if (!EC_GROUP_get_curve(group, p, a, b, ctx)) {
98         ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
99         goto done;
100     }
101
102     p_bytes = BN_num_bytes(p);
103     buf = OPENSSL_zalloc(p_bytes);
104     if (buf == NULL) {
105         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
106         goto done;
107     }
108
109     if (BN_bn2binpad(a, buf, p_bytes) < 0
110             || !EVP_DigestUpdate(hash, buf, p_bytes)
111             || BN_bn2binpad(b, buf, p_bytes) < 0
112             || !EVP_DigestUpdate(hash, buf, p_bytes)
113             || !EC_POINT_get_affine_coordinates(group,
114                                                 EC_GROUP_get0_generator(group),
115                                                 xG, yG, ctx)
116             || BN_bn2binpad(xG, buf, p_bytes) < 0
117             || !EVP_DigestUpdate(hash, buf, p_bytes)
118             || BN_bn2binpad(yG, buf, p_bytes) < 0
119             || !EVP_DigestUpdate(hash, buf, p_bytes)
120             || !EC_POINT_get_affine_coordinates(group,
121                                                 EC_KEY_get0_public_key(key),
122                                                 xA, yA, ctx)
123             || BN_bn2binpad(xA, buf, p_bytes) < 0
124             || !EVP_DigestUpdate(hash, buf, p_bytes)
125             || BN_bn2binpad(yA, buf, p_bytes) < 0
126             || !EVP_DigestUpdate(hash, buf, p_bytes)
127             || !EVP_DigestFinal(hash, out, NULL)) {
128         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
129         goto done;
130     }
131
132     rc = 1;
133
134  done:
135     OPENSSL_free(buf);
136     BN_CTX_free(ctx);
137     EVP_MD_CTX_free(hash);
138     return rc;
139 }
140
141 static BIGNUM *sm2_compute_msg_hash(const EVP_MD *digest,
142                                     const EC_KEY *key,
143                                     const uint8_t *id,
144                                     const size_t id_len,
145                                     const uint8_t *msg, size_t msg_len)
146 {
147     EVP_MD_CTX *hash = EVP_MD_CTX_new();
148     const int md_size = EVP_MD_size(digest);
149     uint8_t *z = NULL;
150     BIGNUM *e = NULL;
151     EVP_MD *fetched_digest = NULL;
152     OSSL_LIB_CTX *libctx = ec_key_get_libctx(key);
153     const char *propq = ec_key_get0_propq(key);
154
155     if (md_size < 0) {
156         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST);
157         goto done;
158     }
159
160     z = OPENSSL_zalloc(md_size);
161     if (hash == NULL || z == NULL) {
162         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
163         goto done;
164     }
165
166     fetched_digest = EVP_MD_fetch(libctx, EVP_MD_name(digest), propq);
167     if (fetched_digest == NULL) {
168         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
169         goto done;
170     }
171
172     if (!sm2_compute_z_digest(z, fetched_digest, id, id_len, key)) {
173         /* SM2err already called */
174         goto done;
175     }
176
177     if (!EVP_DigestInit(hash, fetched_digest)
178             || !EVP_DigestUpdate(hash, z, md_size)
179             || !EVP_DigestUpdate(hash, msg, msg_len)
180                /* reuse z buffer to hold H(Z || M) */
181             || !EVP_DigestFinal(hash, z, NULL)) {
182         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
183         goto done;
184     }
185
186     e = BN_bin2bn(z, md_size, NULL);
187     if (e == NULL)
188         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
189
190  done:
191     EVP_MD_free(fetched_digest);
192     OPENSSL_free(z);
193     EVP_MD_CTX_free(hash);
194     return e;
195 }
196
197 static ECDSA_SIG *sm2_sig_gen(const EC_KEY *key, const BIGNUM *e)
198 {
199     const BIGNUM *dA = EC_KEY_get0_private_key(key);
200     const EC_GROUP *group = EC_KEY_get0_group(key);
201     const BIGNUM *order = EC_GROUP_get0_order(group);
202     ECDSA_SIG *sig = NULL;
203     EC_POINT *kG = NULL;
204     BN_CTX *ctx = NULL;
205     BIGNUM *k = NULL;
206     BIGNUM *rk = NULL;
207     BIGNUM *r = NULL;
208     BIGNUM *s = NULL;
209     BIGNUM *x1 = NULL;
210     BIGNUM *tmp = NULL;
211     OSSL_LIB_CTX *libctx = ec_key_get_libctx(key);
212
213     kG = EC_POINT_new(group);
214     ctx = BN_CTX_new_ex(libctx);
215     if (kG == NULL || ctx == NULL) {
216         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
217         goto done;
218     }
219
220     BN_CTX_start(ctx);
221     k = BN_CTX_get(ctx);
222     rk = BN_CTX_get(ctx);
223     x1 = BN_CTX_get(ctx);
224     tmp = BN_CTX_get(ctx);
225     if (tmp == NULL) {
226         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
227         goto done;
228     }
229
230     /*
231      * These values are returned and so should not be allocated out of the
232      * context
233      */
234     r = BN_new();
235     s = BN_new();
236
237     if (r == NULL || s == NULL) {
238         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
239         goto done;
240     }
241
242     for (;;) {
243         if (!BN_priv_rand_range_ex(k, order, ctx)) {
244             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
245             goto done;
246         }
247
248         if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx)
249                 || !EC_POINT_get_affine_coordinates(group, kG, x1, NULL,
250                                                     ctx)
251                 || !BN_mod_add(r, e, x1, order, ctx)) {
252             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
253             goto done;
254         }
255
256         /* try again if r == 0 or r+k == n */
257         if (BN_is_zero(r))
258             continue;
259
260         if (!BN_add(rk, r, k)) {
261             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
262             goto done;
263         }
264
265         if (BN_cmp(rk, order) == 0)
266             continue;
267
268         if (!BN_add(s, dA, BN_value_one())
269                 || !ec_group_do_inverse_ord(group, s, s, ctx)
270                 || !BN_mod_mul(tmp, dA, r, order, ctx)
271                 || !BN_sub(tmp, k, tmp)
272                 || !BN_mod_mul(s, s, tmp, order, ctx)) {
273             ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
274             goto done;
275         }
276
277         sig = ECDSA_SIG_new();
278         if (sig == NULL) {
279             ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
280             goto done;
281         }
282
283          /* takes ownership of r and s */
284         ECDSA_SIG_set0(sig, r, s);
285         break;
286     }
287
288  done:
289     if (sig == NULL) {
290         BN_free(r);
291         BN_free(s);
292     }
293
294     BN_CTX_free(ctx);
295     EC_POINT_free(kG);
296     return sig;
297 }
298
299 static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig,
300                           const BIGNUM *e)
301 {
302     int ret = 0;
303     const EC_GROUP *group = EC_KEY_get0_group(key);
304     const BIGNUM *order = EC_GROUP_get0_order(group);
305     BN_CTX *ctx = NULL;
306     EC_POINT *pt = NULL;
307     BIGNUM *t = NULL;
308     BIGNUM *x1 = NULL;
309     const BIGNUM *r = NULL;
310     const BIGNUM *s = NULL;
311     OSSL_LIB_CTX *libctx = ec_key_get_libctx(key);
312
313     ctx = BN_CTX_new_ex(libctx);
314     pt = EC_POINT_new(group);
315     if (ctx == NULL || pt == NULL) {
316         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
317         goto done;
318     }
319
320     BN_CTX_start(ctx);
321     t = BN_CTX_get(ctx);
322     x1 = BN_CTX_get(ctx);
323     if (x1 == NULL) {
324         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
325         goto done;
326     }
327
328     /*
329      * B1: verify whether r' in [1,n-1], verification failed if not
330      * B2: verify whether s' in [1,n-1], verification failed if not
331      * B3: set M'~=ZA || M'
332      * B4: calculate e'=Hv(M'~)
333      * B5: calculate t = (r' + s') modn, verification failed if t=0
334      * B6: calculate the point (x1', y1')=[s']G + [t]PA
335      * B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed
336      */
337
338     ECDSA_SIG_get0(sig, &r, &s);
339
340     if (BN_cmp(r, BN_value_one()) < 0
341             || BN_cmp(s, BN_value_one()) < 0
342             || BN_cmp(order, r) <= 0
343             || BN_cmp(order, s) <= 0) {
344         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
345         goto done;
346     }
347
348     if (!BN_mod_add(t, r, s, order, ctx)) {
349         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
350         goto done;
351     }
352
353     if (BN_is_zero(t)) {
354         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
355         goto done;
356     }
357
358     if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx)
359             || !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) {
360         ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
361         goto done;
362     }
363
364     if (!BN_mod_add(t, e, x1, order, ctx)) {
365         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
366         goto done;
367     }
368
369     if (BN_cmp(r, t) == 0)
370         ret = 1;
371
372  done:
373     EC_POINT_free(pt);
374     BN_CTX_free(ctx);
375     return ret;
376 }
377
378 ECDSA_SIG *sm2_do_sign(const EC_KEY *key,
379                        const EVP_MD *digest,
380                        const uint8_t *id,
381                        const size_t id_len,
382                        const uint8_t *msg, size_t msg_len)
383 {
384     BIGNUM *e = NULL;
385     ECDSA_SIG *sig = NULL;
386
387     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
388     if (e == NULL) {
389         /* SM2err already called */
390         goto done;
391     }
392
393     sig = sm2_sig_gen(key, e);
394
395  done:
396     BN_free(e);
397     return sig;
398 }
399
400 int sm2_do_verify(const EC_KEY *key,
401                   const EVP_MD *digest,
402                   const ECDSA_SIG *sig,
403                   const uint8_t *id,
404                   const size_t id_len,
405                   const uint8_t *msg, size_t msg_len)
406 {
407     BIGNUM *e = NULL;
408     int ret = 0;
409
410     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
411     if (e == NULL) {
412         /* SM2err already called */
413         goto done;
414     }
415
416     ret = sm2_sig_verify(key, sig, e);
417
418  done:
419     BN_free(e);
420     return ret;
421 }
422
423 int sm2_internal_sign(const unsigned char *dgst, int dgstlen,
424                       unsigned char *sig, unsigned int *siglen, EC_KEY *eckey)
425 {
426     BIGNUM *e = NULL;
427     ECDSA_SIG *s = NULL;
428     int sigleni;
429     int ret = -1;
430
431     e = BN_bin2bn(dgst, dgstlen, NULL);
432     if (e == NULL) {
433        ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
434        goto done;
435     }
436
437     s = sm2_sig_gen(eckey, e);
438     if (s == NULL) {
439         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
440         goto done;
441     }
442
443     sigleni = i2d_ECDSA_SIG(s, &sig);
444     if (sigleni < 0) {
445        ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
446        goto done;
447     }
448     *siglen = (unsigned int)sigleni;
449
450     ret = 1;
451
452  done:
453     ECDSA_SIG_free(s);
454     BN_free(e);
455     return ret;
456 }
457
458 int sm2_internal_verify(const unsigned char *dgst, int dgstlen,
459                         const unsigned char *sig, int sig_len, EC_KEY *eckey)
460 {
461     ECDSA_SIG *s = NULL;
462     BIGNUM *e = NULL;
463     const unsigned char *p = sig;
464     unsigned char *der = NULL;
465     int derlen = -1;
466     int ret = -1;
467
468     s = ECDSA_SIG_new();
469     if (s == NULL) {
470         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
471         goto done;
472     }
473     if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) {
474         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
475         goto done;
476     }
477     /* Ensure signature uses DER and doesn't have trailing garbage */
478     derlen = i2d_ECDSA_SIG(s, &der);
479     if (derlen != sig_len || memcmp(sig, der, derlen) != 0) {
480         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
481         goto done;
482     }
483
484     e = BN_bin2bn(dgst, dgstlen, NULL);
485     if (e == NULL) {
486         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
487         goto done;
488     }
489
490     ret = sm2_sig_verify(eckey, s, e);
491
492  done:
493     OPENSSL_free(der);
494     BN_free(e);
495     ECDSA_SIG_free(s);
496     return ret;
497 }