Coverage Report

Created: 2026-01-10 06:58

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