• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017-2023 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     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(ossl_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 
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)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_get_size(digest);
149     uint8_t *z = NULL;
150     BIGNUM *e = NULL;
151     EVP_MD *fetched_digest = NULL;
152     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
153     const char *propq = ossl_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_get0_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 (!ossl_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 
sm2_sig_gen(const EC_KEY * key,const BIGNUM * e)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 = ossl_ec_key_get_libctx(key);
212 
213     if (dA == NULL) {
214         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_PRIVATE_KEY);
215         goto done;
216     }
217     kG = EC_POINT_new(group);
218     ctx = BN_CTX_new_ex(libctx);
219     if (kG == NULL || ctx == NULL) {
220         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
221         goto done;
222     }
223 
224     BN_CTX_start(ctx);
225     k = BN_CTX_get(ctx);
226     rk = BN_CTX_get(ctx);
227     x1 = BN_CTX_get(ctx);
228     tmp = BN_CTX_get(ctx);
229     if (tmp == NULL) {
230         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
231         goto done;
232     }
233 
234     /*
235      * These values are returned and so should not be allocated out of the
236      * context
237      */
238     r = BN_new();
239     s = BN_new();
240 
241     if (r == NULL || s == NULL) {
242         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
243         goto done;
244     }
245 
246     /*
247      * A3: Generate a random number k in [1,n-1] using random number generators;
248      * A4: Compute (x1,y1)=[k]G, and convert the type of data x1 to be integer
249      *     as specified in clause 4.2.8 of GM/T 0003.1-2012;
250      * A5: Compute r=(e+x1) mod n. If r=0 or r+k=n, then go to A3;
251      * A6: Compute s=(1/(1+dA)*(k-r*dA)) mod n. If s=0, then go to A3;
252      * A7: Convert the type of data (r,s) to be bit strings according to the details
253      *     in clause 4.2.2 of GM/T 0003.1-2012. Then the signature of message M is (r,s).
254      */
255     for (;;) {
256         if (!BN_priv_rand_range_ex(k, order, 0, ctx)) {
257             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
258             goto done;
259         }
260 
261         if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx)
262                 || !EC_POINT_get_affine_coordinates(group, kG, x1, NULL,
263                                                     ctx)
264                 || !BN_mod_add(r, e, x1, order, ctx)) {
265             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
266             goto done;
267         }
268 
269         /* try again if r == 0 or r+k == n */
270         if (BN_is_zero(r))
271             continue;
272 
273         if (!BN_add(rk, r, k)) {
274             ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
275             goto done;
276         }
277 
278         if (BN_cmp(rk, order) == 0)
279             continue;
280 
281         if (!BN_add(s, dA, BN_value_one())
282                 || !ossl_ec_group_do_inverse_ord(group, s, s, ctx)
283                 || !BN_mod_mul(tmp, dA, r, order, ctx)
284                 || !BN_sub(tmp, k, tmp)
285                 || !BN_mod_mul(s, s, tmp, order, ctx)) {
286             ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
287             goto done;
288         }
289 
290         /* try again if s == 0 */
291         if (BN_is_zero(s))
292             continue;
293 
294         sig = ECDSA_SIG_new();
295         if (sig == NULL) {
296             ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
297             goto done;
298         }
299 
300          /* takes ownership of r and s */
301         ECDSA_SIG_set0(sig, r, s);
302         break;
303     }
304 
305  done:
306     if (sig == NULL) {
307         BN_free(r);
308         BN_free(s);
309     }
310 
311     BN_CTX_free(ctx);
312     EC_POINT_free(kG);
313     return sig;
314 }
315 
sm2_sig_verify(const EC_KEY * key,const ECDSA_SIG * sig,const BIGNUM * e)316 static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig,
317                           const BIGNUM *e)
318 {
319     int ret = 0;
320     const EC_GROUP *group = EC_KEY_get0_group(key);
321     const BIGNUM *order = EC_GROUP_get0_order(group);
322     BN_CTX *ctx = NULL;
323     EC_POINT *pt = NULL;
324     BIGNUM *t = NULL;
325     BIGNUM *x1 = NULL;
326     const BIGNUM *r = NULL;
327     const BIGNUM *s = NULL;
328     OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key);
329 
330     ctx = BN_CTX_new_ex(libctx);
331     pt = EC_POINT_new(group);
332     if (ctx == NULL || pt == NULL) {
333         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
334         goto done;
335     }
336 
337     BN_CTX_start(ctx);
338     t = BN_CTX_get(ctx);
339     x1 = BN_CTX_get(ctx);
340     if (x1 == NULL) {
341         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
342         goto done;
343     }
344 
345     /*
346      * B1: verify whether r' in [1,n-1], verification failed if not
347      * B2: verify whether s' in [1,n-1], verification failed if not
348      * B3: set M'~=ZA || M'
349      * B4: calculate e'=Hv(M'~)
350      * B5: calculate t = (r' + s') modn, verification failed if t=0
351      * B6: calculate the point (x1', y1')=[s']G + [t]PA
352      * B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed
353      */
354 
355     ECDSA_SIG_get0(sig, &r, &s);
356 
357     if (BN_cmp(r, BN_value_one()) < 0
358             || BN_cmp(s, BN_value_one()) < 0
359             || BN_cmp(order, r) <= 0
360             || BN_cmp(order, s) <= 0) {
361         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
362         goto done;
363     }
364 
365     if (!BN_mod_add(t, r, s, order, ctx)) {
366         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
367         goto done;
368     }
369 
370     if (BN_is_zero(t)) {
371         ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE);
372         goto done;
373     }
374 
375     if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx)
376             || !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) {
377         ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB);
378         goto done;
379     }
380 
381     if (!BN_mod_add(t, e, x1, order, ctx)) {
382         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
383         goto done;
384     }
385 
386     if (BN_cmp(r, t) == 0)
387         ret = 1;
388 
389  done:
390     EC_POINT_free(pt);
391     BN_CTX_free(ctx);
392     return ret;
393 }
394 
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)395 ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key,
396                             const EVP_MD *digest,
397                             const uint8_t *id,
398                             const size_t id_len,
399                             const uint8_t *msg, size_t msg_len)
400 {
401     BIGNUM *e = NULL;
402     ECDSA_SIG *sig = NULL;
403 
404     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
405     if (e == NULL) {
406         /* SM2err already called */
407         goto done;
408     }
409 
410     sig = sm2_sig_gen(key, e);
411 
412  done:
413     BN_free(e);
414     return sig;
415 }
416 
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)417 int ossl_sm2_do_verify(const EC_KEY *key,
418                        const EVP_MD *digest,
419                        const ECDSA_SIG *sig,
420                        const uint8_t *id,
421                        const size_t id_len,
422                        const uint8_t *msg, size_t msg_len)
423 {
424     BIGNUM *e = NULL;
425     int ret = 0;
426 
427     e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len);
428     if (e == NULL) {
429         /* SM2err already called */
430         goto done;
431     }
432 
433     ret = sm2_sig_verify(key, sig, e);
434 
435  done:
436     BN_free(e);
437     return ret;
438 }
439 
ossl_sm2_internal_sign(const unsigned char * dgst,int dgstlen,unsigned char * sig,unsigned int * siglen,EC_KEY * eckey)440 int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen,
441                            unsigned char *sig, unsigned int *siglen,
442                            EC_KEY *eckey)
443 {
444     BIGNUM *e = NULL;
445     ECDSA_SIG *s = NULL;
446     int sigleni;
447     int ret = -1;
448 
449     if (sig == NULL) {
450         ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
451         goto done;
452     }
453 
454     e = BN_bin2bn(dgst, dgstlen, NULL);
455     if (e == NULL) {
456        ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
457        goto done;
458     }
459 
460     s = sm2_sig_gen(eckey, e);
461     if (s == NULL) {
462         ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
463         goto done;
464     }
465 
466     sigleni = i2d_ECDSA_SIG(s, &sig);
467     if (sigleni < 0) {
468        ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR);
469        goto done;
470     }
471     *siglen = (unsigned int)sigleni;
472 
473     ret = 1;
474 
475  done:
476     ECDSA_SIG_free(s);
477     BN_free(e);
478     return ret;
479 }
480 
ossl_sm2_internal_verify(const unsigned char * dgst,int dgstlen,const unsigned char * sig,int sig_len,EC_KEY * eckey)481 int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen,
482                              const unsigned char *sig, int sig_len,
483                              EC_KEY *eckey)
484 {
485     ECDSA_SIG *s = NULL;
486     BIGNUM *e = NULL;
487     const unsigned char *p = sig;
488     unsigned char *der = NULL;
489     int derlen = -1;
490     int ret = -1;
491 
492     s = ECDSA_SIG_new();
493     if (s == NULL) {
494         ERR_raise(ERR_LIB_SM2, ERR_R_MALLOC_FAILURE);
495         goto done;
496     }
497     if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) {
498         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
499         goto done;
500     }
501     /* Ensure signature uses DER and doesn't have trailing garbage */
502     derlen = i2d_ECDSA_SIG(s, &der);
503     if (derlen != sig_len || memcmp(sig, der, derlen) != 0) {
504         ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING);
505         goto done;
506     }
507 
508     e = BN_bin2bn(dgst, dgstlen, NULL);
509     if (e == NULL) {
510         ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB);
511         goto done;
512     }
513 
514     ret = sm2_sig_verify(eckey, s, e);
515 
516  done:
517     OPENSSL_free(der);
518     BN_free(e);
519     ECDSA_SIG_free(s);
520     return ret;
521 }
522