Botan 3.14.1
Crypto and TLS for C&
sm2.cpp
Go to the documentation of this file.
1/*
2* SM2 Signatures
3* (C) 2017,2018 Ribose Inc
4* (C) 2018,2024 Jack Lloyd
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/pk_options_readers.h>
10#include <botan/sm2.h>
11
12#include <botan/ec_group.h>
13#include <botan/hash.h>
14#include <botan/internal/ct_utils.h>
15#include <botan/internal/fmt.h>
16#include <botan/internal/keypair.h>
17#include <botan/internal/loadstor.h>
18#include <botan/internal/mem_utils.h>
19#include <botan/internal/pk_ops_impl.h>
20#include <botan/internal/pk_options_impl.h>
21
22namespace Botan {
23
24std::string SM2_PublicKey::algo_name() const {
25 return "SM2";
26}
27
28namespace {
29
30const AlgorithmIdentifier& assert_sm2_algorithm_identifier(const AlgorithmIdentifier& alg_id) {
31 const auto alg_name = alg_id.oid().registered_name();
32 // OpenSSL uses ECDSA's OID for SM2
33 if(alg_name != "SM2" && alg_name != "SM2_Enc" && alg_name != "ECDSA") {
34 throw Decoding_Error(fmt("Unexpected AlgorithmIdentifier OID {} in association with SM2 key", alg_id.oid()));
35 }
36
37 return alg_id; // NOLINT(*-return-const-ref-from-parameter)
38}
39
40} // namespace
41
42SM2_PublicKey::SM2_PublicKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
43 EC_PublicKey(assert_sm2_algorithm_identifier(alg_id), key_bits) {}
44
46 return domain().get_order_bytes();
47}
48
49std::unique_ptr<Public_Key> SM2_PrivateKey::public_key() const {
50 return std::make_unique<SM2_Signature_PublicKey>(domain(), public_ec_point());
51}
52
53bool SM2_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
54 if(!EC_PrivateKey::check_key(rng, strong)) {
55 return false;
56 }
57
58 // SM2 has an oddity in private key generation when compared to
59 // other EC*DSA style signature algorithms described in ISO14888-3:
60 // the private key x MUST be in [0, q-1) instead of [0, q).
61 //
62 // The lower bound is already checked by the default impl
63 if(private_value() >= domain().get_order() - 1) {
64 return false;
65 }
66
67 if(!strong) {
68 return true;
69 }
70
71 return KeyPair::signature_consistency_check(rng, *this, "user@example.com,SM3");
72}
73
74SM2_PrivateKey::SM2_PrivateKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
75 EC_PrivateKey(assert_sm2_algorithm_identifier(alg_id), key_bits),
76 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
77 m_da_inv_legacy(m_da_inv.to_bigint()) {
78 if(m_da_inv.is_zero()) {
79 throw Decoding_Error("SM2 private key cannot equal n-1");
80 }
81}
82
84 EC_PrivateKey(group, x),
85 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
86 m_da_inv_legacy(m_da_inv.to_bigint()) {
87 if(m_da_inv.is_zero()) {
88 throw Decoding_Error("SM2 private key cannot equal n-1");
89 }
90}
91
92namespace {
93
94// Avoid the (unlikely) case of random generating an invalid key of n - 1
95EC_Scalar generate_sm2_private_key(RandomNumberGenerator& rng, const EC_Group& group) {
96 const auto one = EC_Scalar::one(group);
97
98 for(;;) {
99 // EC_Scalar::random never returns zero
100 auto x = EC_Scalar::random(group, rng);
101 BOTAN_ASSERT_NOMSG(x.is_nonzero());
102 if((x + one).is_nonzero()) {
103 return x;
104 }
105 }
106}
107
108} // namespace
109
111 SM2_PrivateKey(group, generate_sm2_private_key(rng, group)) {}
112
114 EC_PrivateKey(rng, group, x),
115 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
116 m_da_inv_legacy(m_da_inv.to_bigint()) {
117 if(m_da_inv.is_zero()) {
118 throw Decoding_Error("SM2 private key cannot equal n-1");
119 }
120}
121
122#if defined(BOTAN_HAS_LEGACY_EC_POINT)
123std::vector<uint8_t> sm2_compute_za(HashFunction& hash,
124 std::string_view user_id,
125 const EC_Group& group,
126 const EC_Point& pubkey) {
127 const auto apoint = EC_AffinePoint(group, pubkey);
128 return sm2_compute_za(hash, user_id, group, apoint);
129}
130#endif
131
132namespace {
133
134std::vector<uint8_t> sm2_compute_za(HashFunction& hash,
135 std::span<const uint8_t> user_id,
136 const EC_Group& group,
137 const EC_AffinePoint& pubkey) {
138 if(user_id.size() >= 8192) {
139 throw Invalid_Argument("SM2 user id too long to represent");
140 }
141
142 const uint16_t uid_len = static_cast<uint16_t>(8 * user_id.size());
143
144 hash.update(get_byte<0>(uid_len));
145 hash.update(get_byte<1>(uid_len));
146 hash.update(user_id);
147
148 const size_t p_bytes = group.get_p_bytes();
149
150 hash.update(group.get_a().serialize(p_bytes));
151 hash.update(group.get_b().serialize(p_bytes));
152 hash.update(group.get_g_x().serialize(p_bytes));
153 hash.update(group.get_g_y().serialize(p_bytes));
154 hash.update(pubkey.xy_bytes());
155
156 return hash.final<std::vector<uint8_t>>();
157}
158
159} // namespace
160
161std::vector<uint8_t> sm2_compute_za(HashFunction& hash,
162 std::string_view user_id,
163 const EC_Group& group,
164 const EC_AffinePoint& pubkey) {
165 return sm2_compute_za(hash, as_span_of_bytes(user_id), group, pubkey);
166}
167
168namespace {
169
170// GM/T 0009-2012 specifies this as the default userid
171// "1234567812345678";
172std::vector<uint8_t> sm2_default_userid() {
173 return {
174 // clang-format off
175 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
176 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
177 // clang-format on
178 };
179}
180
181// SM3 is the only hash specified for use with SM2, so it is the default
182std::string sm2_hash_function(const PK_Signature_Options_Reader& options) {
183 return options.hash_function().value_or("SM3");
184}
185
186/*
187* The input to the signature equation: normally e = H(ZA || M), but if the
188* caller provides the digest directly then no ZA is computed and the context
189* is not used.
190*/
191class SM2_Signature_Input final {
192 public:
193 SM2_Signature_Input(const PK_Signature_Options_Reader& options,
194 const EC_Group& group,
195 const EC_AffinePoint& pubkey) :
196 m_group(group) {
197 if(options.using_externally_computed_prehash()) {
198 if(auto prehash = externally_computed_prehash_name(options)) {
199 m_prehash_name = *prehash;
200 m_expected_digest_len = HashFunction::create_or_throw(*prehash)->output_length();
201 }
202 } else {
203 auto context = options.context().value_or(sm2_default_userid());
204
205 m_hash = HashFunction::create_or_throw(sm2_hash_function(options));
206 // ZA=H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
207 m_za = sm2_compute_za(*m_hash, context, m_group, pubkey);
208 m_hash->update(m_za);
209 }
210 }
211
212 void update(std::span<const uint8_t> input) {
213 if(m_hash) {
214 m_hash->update(input);
215 } else {
216 m_digest.insert(m_digest.end(), input.begin(), input.end());
217 }
218 }
219
220 EC_Scalar final_e() {
221 if(m_hash) {
222 auto e = EC_Scalar::from_bytes_mod_order(m_group, m_hash->final());
223 // prepend ZA for next signature if any
224 m_hash->update(m_za);
225 return e;
226 }
227
229 std::swap(digest, m_digest);
230
231 if(m_expected_digest_len > 0 && digest.size() != m_expected_digest_len) {
232 throw Invalid_Argument(fmt("SM2 was configured to use a {} byte {} prehash but was given {} bytes",
233 m_expected_digest_len,
234 m_prehash_name,
235 digest.size()));
236 }
237
238 return EC_Scalar::from_bytes_mod_order(m_group, digest);
239 }
240
241 std::string hash_function() const {
242 if(m_hash) {
243 return m_hash->name();
244 }
245 return m_prehash_name.empty() ? "Raw" : m_prehash_name;
246 }
247
248 private:
249 const EC_Group m_group;
250 std::vector<uint8_t> m_za;
251 std::unique_ptr<HashFunction> m_hash;
252 secure_vector<uint8_t> m_digest;
253 std::string m_prehash_name;
254 size_t m_expected_digest_len = 0;
255};
256
257/**
258* SM2 signature operation
259*/
260class SM2_Signature_Operation final : public PK_Ops::Signature {
261 public:
262 SM2_Signature_Operation(const SM2_PrivateKey& sm2, const PK_Signature_Options_Reader& options) :
263 m_group(sm2.domain()),
264 m_x(sm2._private_key()),
265 m_da_inv(sm2._get_da_inv()),
266 m_input(options, m_group, sm2.public_ec_point()) {}
267
268 size_t signature_length() const override { return 2 * m_group.get_order_bytes(); }
269
270 void update(std::span<const uint8_t> input) override { m_input.update(input); }
271
272 std::vector<uint8_t> sign(RandomNumberGenerator& rng) override;
273
274 std::string hash_function() const override { return m_input.hash_function(); }
275
276 private:
277 const EC_Group m_group;
278 const EC_Scalar m_x;
279 const EC_Scalar m_da_inv;
280 SM2_Signature_Input m_input;
281};
282
283std::vector<uint8_t> SM2_Signature_Operation::sign(RandomNumberGenerator& rng) {
284 const auto e = m_input.final_e();
285
286 const auto scope = CT::scoped_poison(m_x, m_da_inv);
287
288 const auto k = EC_Scalar::random(m_group, rng);
289 CT::poison(k);
290
291 const auto r = EC_Scalar::gk_x_mod_order(k, rng) + e;
292 const auto s = (k - r * m_x) * m_da_inv;
293
294 CT::unpoison_all(r, s);
295
296 const auto rs = r + s;
297
298 // With overwhelming probability, a bug rather than actual zero r/s
299 if(r.is_zero() || s.is_zero() || rs.is_zero()) {
300 throw Internal_Error("During SM2 signature generated zero r/s");
301 }
302
303 return EC_Scalar::serialize_pair(r, s);
304}
305
306/**
307* SM2 verification operation
308*/
309class SM2_Verification_Operation final : public PK_Ops::Verification {
310 public:
311 SM2_Verification_Operation(const SM2_PublicKey& sm2, const PK_Signature_Options_Reader& options) :
312 m_group(sm2.domain()), m_gy_mul(sm2.public_ec_point()), m_input(options, m_group, sm2.public_ec_point()) {}
313
314 void update(std::span<const uint8_t> input) override { m_input.update(input); }
315
316 bool is_valid_signature(std::span<const uint8_t> sig) override;
317
318 std::string hash_function() const override { return m_input.hash_function(); }
319
320 private:
321 const EC_Group m_group;
322 const EC_Group::Mul2Table m_gy_mul;
323 SM2_Signature_Input m_input;
324};
325
326bool SM2_Verification_Operation::is_valid_signature(std::span<const uint8_t> sig) {
327 const auto e = m_input.final_e();
328
329 if(auto rs = EC_Scalar::deserialize_pair(m_group, sig)) {
330 const auto& [r, s] = rs.value();
331
332 if(r.is_nonzero() && s.is_nonzero()) {
333 const auto t = r + s;
334 if(t.is_nonzero()) {
335 // Check if r - e = x_coord(g*s + y*t) % n
336 return m_gy_mul.mul2_vartime_x_mod_order_eq(r - e, s, t);
337 }
338 }
339 }
340 return false;
341}
342
343} // namespace
344
345std::unique_ptr<Private_Key> SM2_PublicKey::generate_another(RandomNumberGenerator& rng) const {
346 return std::make_unique<SM2_PrivateKey>(rng, domain());
347}
348
349std::unique_ptr<PK_Ops::Verification> SM2_PublicKey::_create_verification_op(
350 const PK_Signature_Options_Reader& options) const {
352
353 return std::make_unique<SM2_Verification_Operation>(*this, options);
354}
355
356std::unique_ptr<PK_Ops::Signature> SM2_PrivateKey::_create_signature_op(
357 RandomNumberGenerator& rng, const PK_Signature_Options_Reader& options) const {
358 BOTAN_UNUSED(rng);
359
361
362 return std::make_unique<SM2_Signature_Operation>(*this, options);
363}
364
365} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
const OID & oid() const
Definition asn1_obj.h:688
bool mul2_vartime_x_mod_order_eq(const EC_Scalar &v, const EC_Scalar &x, const EC_Scalar &y) const
Definition ec_group.cpp:987
size_t get_order_bytes() const
Definition ec_group.cpp:733
const EC_Scalar & _private_key() const
Definition ecc_key.cpp:135
const BigInt & private_value() const
Definition ecc_key.cpp:130
EC_PrivateKey(const EC_PrivateKey &other)=default
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition ecc_key.cpp:237
const EC_Group & domain() const
Definition ecc_key.cpp:76
const EC_AffinePoint & public_ec_point() const
Definition ecc_key.cpp:88
EC_PublicKey(const EC_PublicKey &other)=default
static EC_Scalar one(const EC_Group &group)
Definition ec_scalar.cpp:80
static EC_Scalar from_bytes_mod_order(const EC_Group &group, std::span< const uint8_t > bytes)
Definition ec_scalar.cpp:68
static EC_Scalar random(const EC_Group &group, RandomNumberGenerator &rng)
Definition ec_scalar.cpp:76
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:311
std::optional< std::string > registered_name() const
Definition asn1_oid.cpp:149
std::unique_ptr< Public_Key > public_key() const override
Definition sm2.cpp:49
std::unique_ptr< PK_Ops::Signature > _create_signature_op(RandomNumberGenerator &rng, const PK_Signature_Options_Reader &options) const override
Definition sm2.cpp:356
SM2_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition sm2.cpp:74
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition sm2.cpp:53
std::unique_ptr< PK_Ops::Verification > _create_verification_op(const PK_Signature_Options_Reader &options) const override
Definition sm2.cpp:349
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const final
Definition sm2.cpp:345
std::optional< size_t > _signature_element_size_for_DER_encoding() const override
Definition sm2.cpp:45
std::string algo_name() const override
Definition sm2.cpp:24
bool signature_consistency_check(RandomNumberGenerator &rng, const Private_Key &private_key, const Public_Key &public_key, std::string_view padding)
Definition keypair.cpp:49
constexpr uint8_t get_byte(T input)
Definition loadstor.h:79
std::span< const uint8_t > as_span_of_bytes(const char *s, size_t len)
Definition mem_utils.h:59
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
void require_software_provider(const OptionsT &options, std::string_view algo_name)
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
std::vector< uint8_t > sm2_compute_za(HashFunction &hash, std::string_view user_id, const EC_Group &group, const EC_AffinePoint &pubkey)
Definition sm2.cpp:161