xref: /freebsd/crypto/openssl/crypto/sm2/sm2_sign.c (revision 0d0c8621fd181e507f0fb50ffcca606faf66a8c2)
1 /*
2  * Copyright 2017-2024 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" /* ossl_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 
ossl_sm2_compute_z_digest(uint8_t * out,const EVP_MD * digest,const uint8_t * id,const size_t id_len,const EC_KEY * key)24 int ossl_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     const EC_POINT *pubkey = EC_KEY_get0_public_key(key);
33     BN_CTX *ctx = NULL;
34     EVP_MD_CTX *hash = NULL;
35     BIGNUM *p = NULL;
36     BIGNUM *a = NULL;
37     BIGNUM *b = NULL;
38     BIGNUM *xG = NULL;
39     BIGNUM *yG = NULL;
40     BIGNUM *xA = NULL;
41     BIGNUM *yA = NULL;
42     int p_bytes = 0;
43     uint8_t *buf = NULL;
44     uint16_t entl = 0;
45     uint8_t e_byte = 0;
46 
47     /* SM2 Signatures require a public key, check for it */
48     if (pubkey == NULL) {
49         ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
50         goto done;
51     }
52 
53     hash = EVP_MD_CTX_new();
54     ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(key));
55     if (hash == NULL || ctx == NULL) {
56         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
57         goto done;
58     }
59 
60     p = BN_CTX_get(ctx);
61     a = BN_CTX_get(ctx);
62     b = BN_CTX_get(ctx);
63     xG = BN_CTX_get(ctx);
64     yG = BN_CTX_get(ctx);
65     xA = BN_CTX_get(ctx);
66     yA = BN_CTX_get(ctx);
67 
68     if (yA == NULL) {
69         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
70         goto done;
71     }
72 
73     if (!EVP_DigestInit(hash, digest)) {
74         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
75         goto done;
76     }
77 
78     /* Z = h(ENTL || ID || a || b || xG || yG || xA || yA) */
79 
80     if (id_len >= (UINT16_MAX / 8)) {
81         /* too large */
82         ERR_raise(ERR_LIB_SM2, SM2_R_ID_TOO_LARGE);
83         goto done;
84     }
85 
86     entl = (uint16_t)(8 * id_len);
87 
88     e_byte = entl >> 8;
89     if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
90         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
91         goto done;
92     }
93     e_byte = entl & 0xFF;
94     if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
95         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
96         goto done;
97     }
98 
99     if (id_len > 0 && !EVP_DigestUpdate(hash, id, id_len)) {
100         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
101         goto done;
102     }
103 
104     if (!EC_GROUP_get_curve(group, p, a, b, ctx)) {
105         ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
106         goto done;
107     }
108 
109     p_bytes = BN_num_bytes(p);
110     buf = OPENSSL_zalloc(p_bytes);
111     if (buf == NULL) {
112         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
113         goto done;
114     }
115 
116     if (BN_bn2binpad(a, buf, p_bytes) < 0
117             || !EVP_DigestUpdate(hash, buf, p_bytes)
118             || BN_bn2binpad(b, buf, p_bytes) < 0
119             || !EVP_DigestUpdate(hash, buf, p_bytes)
120             || !EC_POINT_get_affine_coordinates(group,
121                                                 EC_GROUP_get0_generator(group),
122                                                 xG, yG, ctx)
123             || BN_bn2binpad(xG, buf, p_bytes) < 0
124             || !EVP_DigestUpdate(hash, buf, p_bytes)
125             || BN_bn2binpad(yG, buf, p_bytes) < 0
126             || !EVP_DigestUpdate(hash, buf, p_bytes)
127             || !EC_POINT_get_affine_coordinates(group,
128                                                 pubkey,
129                                                 xA, yA, ctx)
130             || BN_bn2binpad(xA, buf, p_bytes) < 0
131             || !EVP_DigestUpdate(hash, buf, p_bytes)
132             || BN_bn2binpad(yA, buf, p_bytes) < 0
133             || !EVP_DigestUpdate(hash, buf, p_bytes)
134             || !EVP_DigestFinal(hash, out, NULL)) {
135         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
136         goto done;
137     }
138 
139     rc = 1;
140 
141  done:
142     OPENSSL_free(buf);
143     BN_CTX_free(ctx);
144     EVP_MD_CTX_free(hash);
145     return rc;
146 }
147 
sm2_compute_msg_hash(const EVP_MD * digest,const EC_KEY * key,const uint8_t * id,const size_t id_len,const uint8_t * msg,size_t msg_len)148 static BIGNUM *sm2_compute_msg_hash(const EVP_MD *digest,
149                                     const EC_KEY *key,
150                                     const uint8_t *id,
151                                     const size_t id_len,
152                                     const uint8_t *msg, size_t msg_len)
153 {
154     EVP_MD_CTX *hash = EVP_MD_CTX_new();
155     const int md_size = EVP_MD_get_size(digest);
156     uint8_t *z = NULL;
157     BIGNUM *e = NULL;
158     EVP_MD *fetched_digest = NULL;
159     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
160     const char *propq = ossl_ec_key_get0_propq(key);
161 
162     if (md_size < 0) {
163         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST);
164         goto done;
165     }
166 
167     z = OPENSSL_zalloc(md_size);
168     if (hash == NULL || z == NULL) {
169         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
170         goto done;
171     }
172 
173     fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq);
174     if (fetched_digest == NULL) {
175         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
176         goto done;
177     }
178 
179     if (!ossl_sm2_compute_z_digest(z, fetched_digest, id, id_len, key)) {
180         /* SM2err already called */
181         goto done;
182     }
183 
184     if (!EVP_DigestInit(hash, fetched_digest)
185             || !EVP_DigestUpdate(hash, z, md_size)
186             || !EVP_DigestUpdate(hash, msg, msg_len)
187                /* reuse z buffer to hold H(Z || M) */
188             || !EVP_DigestFinal(hash, z, NULL)) {
189         ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB);
190         goto done;
191     }
192 
193     e = BN_bin2bn(z, md_size, NULL);
194     if (e == NULL)
195         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
196 
197  done:
198     EVP_MD_free(fetched_digest);
199     OPENSSL_free(z);
200     EVP_MD_CTX_free(hash);
201     return e;
202 }
203 
sm2_sig_gen(const EC_KEY * key,const BIGNUM * e)204 static ECDSA_SIG *sm2_sig_gen(const EC_KEY *key, const BIGNUM *e)
205 {
206     const BIGNUM *dA = EC_KEY_get0_private_key(key);
207     const EC_GROUP *group = EC_KEY_get0_group(key);
208     const BIGNUM *order = EC_GROUP_get0_order(group);
209     ECDSA_SIG *sig = NULL;
210     EC_POINT *kG = NULL;
211     BN_CTX *ctx = NULL;
212     BIGNUM *k = NULL;
213     BIGNUM *rk = NULL;
214     BIGNUM *r = NULL;
215     BIGNUM *s = NULL;
216     BIGNUM *x1 = NULL;
217     BIGNUM *tmp = NULL;
218     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
219 
220     kG = EC_POINT_new(group);
221     ctx = BN_CTX_new_ex(libctx);
222     if (kG == NULL || ctx == NULL) {
223         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
224         goto done;
225     }
226 
227     BN_CTX_start(ctx);
228     k = BN_CTX_get(ctx);
229     rk = BN_CTX_get(ctx);
230     x1 = BN_CTX_get(ctx);
231     tmp = BN_CTX_get(ctx);
232     if (tmp == NULL) {
233         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
234         goto done;
235     }
236 
237     /*
238      * These values are returned and so should not be allocated out of the
239      * context
240      */
241     r = BN_new();
242     s = BN_new();
243 
244     if (r == NULL || s == NULL) {
245         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
246         goto done;
247     }
248 
249     /*
250      * A3: Generate a random number k in [1,n-1] using random number generators;
251      * A4: Compute (x1,y1)=[k]G, and convert the type of data x1 to be integer
252      *     as specified in clause 4.2.8 of GM/T 0003.1-2012;
253      * A5: Compute r=(e+x1) mod n. If r=0 or r+k=n, then go to A3;
254      * A6: Compute s=(1/(1+dA)*(k-r*dA)) mod n. If s=0, then go to A3;
255      * A7: Convert the type of data (r,s) to be bit strings according to the details
256      *     in clause 4.2.2 of GM/T 0003.1-2012. Then the signature of message M is (r,s).
257      */
258     for (;;) {
259         if (!BN_priv_rand_range_ex(k, order, 0, ctx)) {
260             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
261             goto done;
262         }
263 
264         if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx)
265                 || !EC_POINT_get_affine_coordinates(group, kG, x1, NULL,
266                                                     ctx)
267                 || !BN_mod_add(r, e, x1, order, ctx)) {
268             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
269             goto done;
270         }
271 
272         /* try again if r == 0 or r+k == n */
273         if (BN_is_zero(r))
274             continue;
275 
276         if (!BN_add(rk, r, k)) {
277             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
278             goto done;
279         }
280 
281         if (BN_cmp(rk, order) == 0)
282             continue;
283 
284         if (!BN_add(s, dA, BN_value_one())
285                 || !ossl_ec_group_do_inverse_ord(group, s, s, ctx)
286                 || !BN_mod_mul(tmp, dA, r, order, ctx)
287                 || !BN_sub(tmp, k, tmp)
288                 || !BN_mod_mul(s, s, tmp, order, ctx)) {
289             ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
290             goto done;
291         }
292 
293         /* try again if s == 0 */
294         if (BN_is_zero(s))
295             continue;
296 
297         sig = ECDSA_SIG_new();
298         if (sig == NULL) {
299             ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
300             goto done;
301         }
302 
303          /* takes ownership of r and s */
304         ECDSA_SIG_set0(sig, r, s);
305         break;
306     }
307 
308  done:
309     if (sig == NULL) {
310         BN_free(r);
311         BN_free(s);
312     }
313 
314     BN_CTX_free(ctx);
315     EC_POINT_free(kG);
316     return sig;
317 }
318 
sm2_sig_verify(const EC_KEY * key,const ECDSA_SIG * sig,const BIGNUM * e)319 static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig,
320                           const BIGNUM *e)
321 {
322     int ret = 0;
323     const EC_GROUP *group = EC_KEY_get0_group(key);
324     const BIGNUM *order = EC_GROUP_get0_order(group);
325     BN_CTX *ctx = NULL;
326     EC_POINT *pt = NULL;
327     BIGNUM *t = NULL;
328     BIGNUM *x1 = NULL;
329     const BIGNUM *r = NULL;
330     const BIGNUM *s = NULL;
331     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
332 
333     ctx = BN_CTX_new_ex(libctx);
334     if (ctx == NULL) {
335         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
336         goto done;
337     }
338     BN_CTX_start(ctx);
339     t = BN_CTX_get(ctx);
340     x1 = BN_CTX_get(ctx);
341     if (x1 == NULL) {
342         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
343         goto done;
344     }
345 
346     pt = EC_POINT_new(group);
347     if (pt == NULL) {
348         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
349         goto done;
350     }
351 
352     /*
353      * B1: verify whether r' in [1,n-1], verification failed if not
354      * B2: verify whether s' in [1,n-1], verification failed if not
355      * B3: set M'~=ZA || M'
356      * B4: calculate e'=Hv(M'~)
357      * B5: calculate t = (r' + s') modn, verification failed if t=0
358      * B6: calculate the point (x1', y1')=[s']G + [t]PA
359      * B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed
360      */
361 
362     ECDSA_SIG_get0(sig, &r, &s);
363 
364     if (BN_cmp(r, BN_value_one()) < 0
365             || BN_cmp(s, BN_value_one()) < 0
366             || BN_cmp(order, r) <= 0
367             || BN_cmp(order, s) <= 0) {
368         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
369         goto done;
370     }
371 
372     if (!BN_mod_add(t, r, s, order, ctx)) {
373         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
374         goto done;
375     }
376 
377     if (BN_is_zero(t)) {
378         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
379         goto done;
380     }
381 
382     if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx)
383             || !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) {
384         ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
385         goto done;
386     }
387 
388     if (!BN_mod_add(t, e, x1, order, ctx)) {
389         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
390         goto done;
391     }
392 
393     if (BN_cmp(r, t) == 0)
394         ret = 1;
395 
396  done:
397     EC_POINT_free(pt);
398     BN_CTX_free(ctx);
399     return ret;
400 }
401 
ossl_sm2_do_sign(const EC_KEY * key,const EVP_MD * digest,const uint8_t * id,const size_t id_len,const uint8_t * msg,size_t msg_len)402 ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key,
403                             const EVP_MD *digest,
404                             const uint8_t *id,
405                             const size_t id_len,
406                             const uint8_t *msg, size_t msg_len)
407 {
408     BIGNUM *e = NULL;
409     ECDSA_SIG *sig = NULL;
410 
411     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
412     if (e == NULL) {
413         /* SM2err already called */
414         goto done;
415     }
416 
417     sig = sm2_sig_gen(key, e);
418 
419  done:
420     BN_free(e);
421     return sig;
422 }
423 
ossl_sm2_do_verify(const EC_KEY * key,const EVP_MD * digest,const ECDSA_SIG * sig,const uint8_t * id,const size_t id_len,const uint8_t * msg,size_t msg_len)424 int ossl_sm2_do_verify(const EC_KEY *key,
425                        const EVP_MD *digest,
426                        const ECDSA_SIG *sig,
427                        const uint8_t *id,
428                        const size_t id_len,
429                        const uint8_t *msg, size_t msg_len)
430 {
431     BIGNUM *e = NULL;
432     int ret = 0;
433 
434     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
435     if (e == NULL) {
436         /* SM2err already called */
437         goto done;
438     }
439 
440     ret = sm2_sig_verify(key, sig, e);
441 
442  done:
443     BN_free(e);
444     return ret;
445 }
446 
ossl_sm2_internal_sign(const unsigned char * dgst,int dgstlen,unsigned char * sig,unsigned int * siglen,EC_KEY * eckey)447 int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen,
448                            unsigned char *sig, unsigned int *siglen,
449                            EC_KEY *eckey)
450 {
451     BIGNUM *e = NULL;
452     ECDSA_SIG *s = NULL;
453     int sigleni;
454     int ret = -1;
455 
456     if (sig == NULL) {
457         ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
458         goto done;
459     }
460 
461     e = BN_bin2bn(dgst, dgstlen, NULL);
462     if (e == NULL) {
463        ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
464        goto done;
465     }
466 
467     s = sm2_sig_gen(eckey, e);
468     if (s == NULL) {
469         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
470         goto done;
471     }
472 
473     sigleni = i2d_ECDSA_SIG(s, &sig);
474     if (sigleni < 0) {
475        ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
476        goto done;
477     }
478     *siglen = (unsigned int)sigleni;
479 
480     ret = 1;
481 
482  done:
483     ECDSA_SIG_free(s);
484     BN_free(e);
485     return ret;
486 }
487 
ossl_sm2_internal_verify(const unsigned char * dgst,int dgstlen,const unsigned char * sig,int sig_len,EC_KEY * eckey)488 int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen,
489                              const unsigned char *sig, int sig_len,
490                              EC_KEY *eckey)
491 {
492     ECDSA_SIG *s = NULL;
493     BIGNUM *e = NULL;
494     const unsigned char *p = sig;
495     unsigned char *der = NULL;
496     int derlen = -1;
497     int ret = -1;
498 
499     s = ECDSA_SIG_new();
500     if (s == NULL) {
501         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
502         goto done;
503     }
504     if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) {
505         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
506         goto done;
507     }
508     /* Ensure signature uses DER and doesn't have trailing garbage */
509     derlen = i2d_ECDSA_SIG(s, &der);
510     if (derlen != sig_len || memcmp(sig, der, derlen) != 0) {
511         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
512         goto done;
513     }
514 
515     e = BN_bin2bn(dgst, dgstlen, NULL);
516     if (e == NULL) {
517         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
518         goto done;
519     }
520 
521     ret = sm2_sig_verify(eckey, s, e);
522 
523  done:
524     OPENSSL_free(der);
525     BN_free(e);
526     ECDSA_SIG_free(s);
527     return ret;
528 }
529