Coverage Report

Created: 2023-05-26 06:51

/src/botan/src/lib/pubkey/sm2/sm2.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* SM2 Signatures
3
* (C) 2017,2018 Ribose Inc
4
* (C) 2018 Jack Lloyd
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8
9
#include <botan/sm2.h>
10
11
#include <botan/internal/pk_ops_impl.h>
12
#include <botan/internal/point_mul.h>
13
#include <botan/internal/loadstor.h>
14
#include <botan/numthry.h>
15
#include <botan/internal/keypair.h>
16
#include <botan/hash.h>
17
#include <botan/internal/parsing.h>
18
19
namespace Botan {
20
21
std::string SM2_PublicKey::algo_name() const
22
0
   {
23
0
   return "SM2";
24
0
   }
25
26
std::unique_ptr<Public_Key> SM2_PrivateKey::public_key() const
27
0
   {
28
0
   return std::make_unique<SM2_Signature_PublicKey>(domain(), public_point());
29
0
   }
30
31
bool SM2_PrivateKey::check_key(RandomNumberGenerator& rng,
32
                               bool strong) const
33
0
   {
34
0
   if(!public_point().on_the_curve())
35
0
      return false;
36
37
0
   if(!strong)
38
0
      return true;
39
40
0
   return KeyPair::signature_consistency_check(rng, *this, "user@example.com,SM3");
41
0
   }
42
43
SM2_PrivateKey::SM2_PrivateKey(const AlgorithmIdentifier& alg_id,
44
                               std::span<const uint8_t> key_bits) :
45
   EC_PrivateKey(alg_id, key_bits)
46
0
   {
47
0
   m_da_inv = domain().inverse_mod_order(m_private_key + 1);
48
0
   }
Unexecuted instantiation: Botan::SM2_PrivateKey::SM2_PrivateKey(Botan::AlgorithmIdentifier const&, std::__1::span<unsigned char const, 18446744073709551615ul>)
Unexecuted instantiation: Botan::SM2_PrivateKey::SM2_PrivateKey(Botan::AlgorithmIdentifier const&, std::__1::span<unsigned char const, 18446744073709551615ul>)
49
50
SM2_PrivateKey::SM2_PrivateKey(RandomNumberGenerator& rng,
51
                               const EC_Group& domain,
52
                               const BigInt& x) :
53
   EC_PrivateKey(rng, domain, x)
54
0
   {
55
0
   m_da_inv = domain.inverse_mod_order(m_private_key + 1);
56
0
   }
Unexecuted instantiation: Botan::SM2_PrivateKey::SM2_PrivateKey(Botan::RandomNumberGenerator&, Botan::EC_Group const&, Botan::BigInt const&)
Unexecuted instantiation: Botan::SM2_PrivateKey::SM2_PrivateKey(Botan::RandomNumberGenerator&, Botan::EC_Group const&, Botan::BigInt const&)
57
58
std::vector<uint8_t> sm2_compute_za(HashFunction& hash,
59
                                    std::string_view user_id,
60
                                    const EC_Group& domain,
61
                                    const EC_Point& pubkey)
62
0
   {
63
0
   if(user_id.size() >= 8192)
64
0
      throw Invalid_Argument("SM2 user id too long to represent");
65
66
0
   const uint16_t uid_len = static_cast<uint16_t>(8 * user_id.size());
67
68
0
   hash.update(get_byte<0>(uid_len));
69
0
   hash.update(get_byte<1>(uid_len));
70
0
   hash.update(user_id);
71
72
0
   const size_t p_bytes = domain.get_p_bytes();
73
74
0
   hash.update(BigInt::encode_1363(domain.get_a(), p_bytes));
75
0
   hash.update(BigInt::encode_1363(domain.get_b(), p_bytes));
76
0
   hash.update(BigInt::encode_1363(domain.get_g_x(), p_bytes));
77
0
   hash.update(BigInt::encode_1363(domain.get_g_y(), p_bytes));
78
0
   hash.update(BigInt::encode_1363(pubkey.get_affine_x(), p_bytes));
79
0
   hash.update(BigInt::encode_1363(pubkey.get_affine_y(), p_bytes));
80
81
0
   std::vector<uint8_t> za(hash.output_length());
82
0
   hash.final(za.data());
83
84
0
   return za;
85
0
   }
86
87
namespace {
88
89
/**
90
* SM2 signature operation
91
*/
92
class SM2_Signature_Operation final : public PK_Ops::Signature
93
   {
94
   public:
95
96
      SM2_Signature_Operation(const SM2_PrivateKey& sm2,
97
                              std::string_view ident,
98
                              std::string_view hash) :
99
         m_group(sm2.domain()),
100
         m_x(sm2.private_value()),
101
         m_da_inv(sm2.get_da_inv())
102
0
         {
103
0
         if(hash == "Raw")
104
0
            {
105
            // m_hash is null, m_za is empty
106
0
            }
107
0
         else
108
0
            {
109
0
            m_hash = HashFunction::create_or_throw(hash);
110
            // ZA=H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
111
0
            m_za = sm2_compute_za(*m_hash, ident, m_group, sm2.public_point());
112
0
            m_hash->update(m_za);
113
0
            }
114
0
         }
115
116
0
      size_t signature_length() const override { return 2*m_group.get_order_bytes(); }
117
118
      void update(const uint8_t msg[], size_t msg_len) override
119
0
         {
120
0
         if(m_hash)
121
0
            {
122
0
            m_hash->update(msg, msg_len);
123
0
            }
124
0
         else
125
0
            {
126
0
            m_digest.insert(m_digest.end(), msg, msg + msg_len);
127
0
            }
128
0
         }
129
130
      secure_vector<uint8_t> sign(RandomNumberGenerator& rng) override;
131
132
0
      std::string hash_function() const override { return m_hash->name(); }
133
   private:
134
      const EC_Group m_group;
135
      const BigInt& m_x;
136
      const BigInt& m_da_inv;
137
138
      std::vector<uint8_t> m_za;
139
      secure_vector<uint8_t> m_digest;
140
      std::unique_ptr<HashFunction> m_hash;
141
      std::vector<BigInt> m_ws;
142
   };
143
144
secure_vector<uint8_t>
145
SM2_Signature_Operation::sign(RandomNumberGenerator& rng)
146
0
   {
147
0
   BigInt e;
148
0
   if(m_hash)
149
0
      {
150
0
      e = BigInt::decode(m_hash->final());
151
      // prepend ZA for next signature if any
152
0
      m_hash->update(m_za);
153
0
      }
154
0
   else
155
0
      {
156
0
      e = BigInt::decode(m_digest);
157
0
      m_digest.clear();
158
0
      }
159
160
0
   const BigInt k = m_group.random_scalar(rng);
161
162
0
   const BigInt r = m_group.mod_order(
163
0
      m_group.blinded_base_point_multiply_x(k, rng, m_ws) + e);
164
0
   const BigInt s = m_group.multiply_mod_order(m_da_inv, m_group.mod_order(k - r*m_x));
165
166
0
   return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order().bytes());
167
0
   }
168
169
/**
170
* SM2 verification operation
171
*/
172
class SM2_Verification_Operation final : public PK_Ops::Verification
173
   {
174
   public:
175
      SM2_Verification_Operation(const SM2_PublicKey& sm2,
176
                                 std::string_view ident,
177
                                 std::string_view hash) :
178
         m_group(sm2.domain()),
179
         m_gy_mul(m_group.get_base_point(), sm2.public_point())
180
0
         {
181
0
         if(hash == "Raw")
182
0
            {
183
            // m_hash is null, m_za is empty
184
0
            }
185
0
         else
186
0
            {
187
0
            m_hash = HashFunction::create_or_throw(hash);
188
            // ZA=H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
189
0
            m_za = sm2_compute_za(*m_hash, ident, m_group, sm2.public_point());
190
0
            m_hash->update(m_za);
191
0
            }
192
0
         }
193
194
      void update(const uint8_t msg[], size_t msg_len) override
195
0
         {
196
0
         if(m_hash)
197
0
            {
198
0
            m_hash->update(msg, msg_len);
199
0
            }
200
0
         else
201
0
            {
202
0
            m_digest.insert(m_digest.end(), msg, msg + msg_len);
203
0
            }
204
0
         }
205
206
      bool is_valid_signature(const uint8_t sig[], size_t sig_len) override;
207
208
0
      std::string hash_function() const override { return m_hash->name(); }
209
   private:
210
      const EC_Group m_group;
211
      const EC_Point_Multi_Point_Precompute m_gy_mul;
212
      secure_vector<uint8_t> m_digest;
213
      std::vector<uint8_t> m_za;
214
      std::unique_ptr<HashFunction> m_hash;
215
   };
216
217
bool SM2_Verification_Operation::is_valid_signature(const uint8_t sig[], size_t sig_len)
218
0
   {
219
0
   BigInt e;
220
0
   if(m_hash)
221
0
      {
222
0
      e = BigInt::decode(m_hash->final());
223
      // prepend ZA for next signature if any
224
0
      m_hash->update(m_za);
225
0
      }
226
0
   else
227
0
      {
228
0
      e = BigInt::decode(m_digest);
229
0
      m_digest.clear();
230
0
      }
231
232
0
   if(sig_len != m_group.get_order().bytes()*2)
233
0
      return false;
234
235
0
   const BigInt r(sig, sig_len / 2);
236
0
   const BigInt s(sig + sig_len / 2, sig_len / 2);
237
238
0
   if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())
239
0
      return false;
240
241
0
   const BigInt t = m_group.mod_order(r + s);
242
243
0
   if(t == 0)
244
0
      return false;
245
246
0
   const EC_Point R = m_gy_mul.multi_exp(s, t);
247
248
   // ???
249
0
   if(R.is_zero())
250
0
      return false;
251
252
0
   return (m_group.mod_order(R.get_affine_x() + e) == r);
253
0
   }
254
255
void parse_sm2_param_string(std::string_view params,
256
                            std::string& userid,
257
                            std::string& hash)
258
0
   {
259
   // GM/T 0009-2012 specifies this as the default userid
260
0
   const std::string default_userid = "1234567812345678";
261
262
   // defaults:
263
0
   userid = default_userid;
264
0
   hash = "SM3";
265
266
   /*
267
   * SM2 parameters have the following possible formats:
268
   * Ident [since 2.2.0]
269
   * Ident,Hash [since 2.3.0]
270
   */
271
272
0
   auto comma = params.find(',');
273
0
   if(comma == std::string::npos)
274
0
      {
275
0
      userid = params;
276
0
      }
277
0
   else
278
0
      {
279
0
      userid = params.substr(0, comma);
280
0
      hash = params.substr(comma+1, std::string::npos);
281
0
      }
282
0
   }
283
284
}
285
286
std::unique_ptr<PK_Ops::Verification>
287
SM2_PublicKey::create_verification_op(std::string_view params,
288
                                      std::string_view provider) const
289
0
   {
290
0
   if(provider == "base" || provider.empty())
291
0
      {
292
0
      std::string userid, hash;
293
0
      parse_sm2_param_string(params, userid, hash);
294
0
      return std::make_unique<SM2_Verification_Operation>(*this, userid, hash);
295
0
      }
296
297
0
   throw Provider_Not_Found(algo_name(), provider);
298
0
   }
299
300
std::unique_ptr<PK_Ops::Signature>
301
SM2_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
302
                                    std::string_view params,
303
                                    std::string_view provider) const
304
0
   {
305
0
   if(provider == "base" || provider.empty())
306
0
      {
307
0
      std::string userid, hash;
308
0
      parse_sm2_param_string(params, userid, hash);
309
0
      return std::make_unique<SM2_Signature_Operation>(*this, userid, hash);
310
0
      }
311
312
0
   throw Provider_Not_Found(algo_name(), provider);
313
0
   }
314
315
}