Botan 3.7.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/sm2.h>
10
11#include <botan/hash.h>
12#include <botan/internal/keypair.h>
13#include <botan/internal/loadstor.h>
14#include <botan/internal/parsing.h>
15#include <botan/internal/pk_ops_impl.h>
16
17namespace Botan {
18
19std::string SM2_PublicKey::algo_name() const {
20 return "SM2";
21}
22
23std::unique_ptr<Public_Key> SM2_PrivateKey::public_key() const {
24 return std::make_unique<SM2_Signature_PublicKey>(domain(), _public_ec_point());
25}
26
27bool SM2_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
28 if(!EC_PrivateKey::check_key(rng, strong)) {
29 return false;
30 }
31
32 // SM2 has an oddity in private key generation when compared to
33 // other EC*DSA style signature algorithms described in ISO14888-3:
34 // the private key x MUST be in [0, q-1) instead of [0, q).
35 //
36 // The lower bound is already checked by the default impl
37 if(private_value() >= domain().get_order() - 1) {
38 return false;
39 }
40
41 if(!strong) {
42 return true;
43 }
44
45 return KeyPair::signature_consistency_check(rng, *this, "user@example.com,SM3");
46}
47
48SM2_PrivateKey::SM2_PrivateKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
49 EC_PrivateKey(alg_id, key_bits),
50 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
51 m_da_inv_legacy(m_da_inv.to_bigint()) {}
52
54 EC_PrivateKey(std::move(group), std::move(x)),
55 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
56 m_da_inv_legacy(m_da_inv.to_bigint()) {}
57
59 EC_PrivateKey(rng, std::move(group)),
60 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
61 m_da_inv_legacy(m_da_inv.to_bigint()) {}
62
64 EC_PrivateKey(rng, std::move(group), x),
65 m_da_inv((this->_private_key() + EC_Scalar::one(domain())).invert()),
66 m_da_inv_legacy(m_da_inv.to_bigint()) {}
67
68std::vector<uint8_t> sm2_compute_za(HashFunction& hash,
69 std::string_view user_id,
70 const EC_Group& group,
71 const EC_AffinePoint& pubkey) {
72 if(user_id.size() >= 8192) {
73 throw Invalid_Argument("SM2 user id too long to represent");
74 }
75
76 const uint16_t uid_len = static_cast<uint16_t>(8 * user_id.size());
77
78 hash.update(get_byte<0>(uid_len));
79 hash.update(get_byte<1>(uid_len));
80 hash.update(user_id);
81
82 const size_t p_bytes = group.get_p_bytes();
83
84 hash.update(group.get_a().serialize(p_bytes));
85 hash.update(group.get_b().serialize(p_bytes));
86 hash.update(group.get_g_x().serialize(p_bytes));
87 hash.update(group.get_g_y().serialize(p_bytes));
88 hash.update(pubkey.xy_bytes());
89
90 return hash.final<std::vector<uint8_t>>();
91}
92
93namespace {
94
95/**
96* SM2 signature operation
97*/
98class SM2_Signature_Operation final : public PK_Ops::Signature {
99 public:
100 SM2_Signature_Operation(const SM2_PrivateKey& sm2, std::string_view ident, std::string_view hash) :
101 m_group(sm2.domain()), m_x(sm2._private_key()), m_da_inv(sm2._get_da_inv()) {
102 if(hash == "Raw") {
103 // m_hash is null, m_za is empty
104 } else {
105 m_hash = HashFunction::create_or_throw(hash);
106 // ZA=H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
107 m_za = sm2_compute_za(*m_hash, ident, m_group, sm2._public_ec_point());
108 m_hash->update(m_za);
109 }
110 }
111
112 size_t signature_length() const override { return 2 * m_group.get_order_bytes(); }
113
114 void update(std::span<const uint8_t> input) override {
115 if(m_hash) {
116 m_hash->update(input);
117 } else {
118 m_digest.insert(m_digest.end(), input.begin(), input.end());
119 }
120 }
121
122 std::vector<uint8_t> sign(RandomNumberGenerator& rng) override;
123
124 std::string hash_function() const override { return m_hash ? m_hash->name() : "Raw"; }
125
126 private:
127 const EC_Group m_group;
128 const EC_Scalar m_x;
129 const EC_Scalar m_da_inv;
130
131 std::vector<uint8_t> m_za;
132 secure_vector<uint8_t> m_digest;
133 std::unique_ptr<HashFunction> m_hash;
134 std::vector<BigInt> m_ws;
135};
136
137std::vector<uint8_t> SM2_Signature_Operation::sign(RandomNumberGenerator& rng) {
138 const auto e = [&]() {
139 if(m_hash) {
140 auto ie = EC_Scalar::from_bytes_mod_order(m_group, m_hash->final());
141 // prepend ZA for next signature if any
142 m_hash->update(m_za);
143 return ie;
144 } else {
145 auto ie = EC_Scalar::from_bytes_mod_order(m_group, m_digest);
146 m_digest.clear();
147 return ie;
148 }
149 }();
150
151 const auto k = EC_Scalar::random(m_group, rng);
152
153 const auto r = EC_Scalar::gk_x_mod_order(k, rng, m_ws) + e;
154 const auto s = (k - r * m_x) * m_da_inv;
155
156 return EC_Scalar::serialize_pair(r, s);
157}
158
159/**
160* SM2 verification operation
161*/
162class SM2_Verification_Operation final : public PK_Ops::Verification {
163 public:
164 SM2_Verification_Operation(const SM2_PublicKey& sm2, std::string_view ident, std::string_view hash) :
165 m_group(sm2.domain()), m_gy_mul(sm2._public_ec_point()) {
166 if(hash == "Raw") {
167 // m_hash is null, m_za is empty
168 } else {
169 m_hash = HashFunction::create_or_throw(hash);
170 // ZA=H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
171 m_za = sm2_compute_za(*m_hash, ident, m_group, sm2._public_ec_point());
172 m_hash->update(m_za);
173 }
174 }
175
176 void update(std::span<const uint8_t> input) override {
177 if(m_hash) {
178 m_hash->update(input);
179 } else {
180 m_digest.insert(m_digest.end(), input.begin(), input.end());
181 }
182 }
183
184 bool is_valid_signature(std::span<const uint8_t> sig) override;
185
186 std::string hash_function() const override { return m_hash ? m_hash->name() : "Raw"; }
187
188 private:
189 const EC_Group m_group;
190 const EC_Group::Mul2Table m_gy_mul;
191 secure_vector<uint8_t> m_digest;
192 std::vector<uint8_t> m_za;
193 std::unique_ptr<HashFunction> m_hash;
194};
195
196bool SM2_Verification_Operation::is_valid_signature(std::span<const uint8_t> sig) {
197 const auto e = [&]() {
198 if(m_hash) {
199 auto ie = EC_Scalar::from_bytes_mod_order(m_group, m_hash->final());
200 // prepend ZA for next signature if any
201 m_hash->update(m_za);
202 return ie;
203 } else {
204 auto ie = EC_Scalar::from_bytes_mod_order(m_group, m_digest);
205 m_digest.clear();
206 return ie;
207 }
208 }();
209
210 if(auto rs = EC_Scalar::deserialize_pair(m_group, sig)) {
211 const auto& [r, s] = rs.value();
212
213 if(r.is_nonzero() && s.is_nonzero()) {
214 const auto t = r + s;
215 if(t.is_nonzero()) {
216 // Check if r - e = x_coord(g*s + y*t) % n
217 return m_gy_mul.mul2_vartime_x_mod_order_eq(r - e, s, t);
218 }
219 }
220 }
221 return false;
222}
223
224void parse_sm2_param_string(std::string_view params, std::string& userid, std::string& hash) {
225 // GM/T 0009-2012 specifies this as the default userid
226 const std::string default_userid = "1234567812345678";
227
228 // defaults:
229 userid = default_userid;
230 hash = "SM3";
231
232 /*
233 * SM2 parameters have the following possible formats:
234 * Ident [since 2.2.0]
235 * Ident,Hash [since 2.3.0]
236 */
237
238 auto comma = params.find(',');
239 if(comma == std::string::npos) {
240 userid = params;
241 } else {
242 userid = params.substr(0, comma);
243 hash = params.substr(comma + 1, std::string::npos);
244 }
245}
246
247} // namespace
248
249std::unique_ptr<Private_Key> SM2_PublicKey::generate_another(RandomNumberGenerator& rng) const {
250 return std::make_unique<SM2_PrivateKey>(rng, domain());
251}
252
253std::unique_ptr<PK_Ops::Verification> SM2_PublicKey::create_verification_op(std::string_view params,
254 std::string_view provider) const {
255 if(provider == "base" || provider.empty()) {
256 std::string userid, hash;
257 parse_sm2_param_string(params, userid, hash);
258 return std::make_unique<SM2_Verification_Operation>(*this, userid, hash);
259 }
260
261 throw Provider_Not_Found(algo_name(), provider);
262}
263
264std::unique_ptr<PK_Ops::Signature> SM2_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
265 std::string_view params,
266 std::string_view provider) const {
267 if(provider == "base" || provider.empty()) {
268 std::string userid, hash;
269 parse_sm2_param_string(params, userid, hash);
270 return std::make_unique<SM2_Signature_Operation>(*this, userid, hash);
271 }
272
273 throw Provider_Not_Found(algo_name(), provider);
274}
275
276} // namespace Botan
T serialize(size_t len) const
Definition bigint.h:712
void update(const uint8_t in[], size_t length)
Definition buf_comp.h:35
void final(uint8_t out[])
Definition buf_comp.h:70
bool mul2_vartime_x_mod_order_eq(const EC_Scalar &v, const EC_Scalar &x, const EC_Scalar &y) const
Definition ec_group.cpp:743
const BigInt & get_b() const
Definition ec_group.cpp:522
const BigInt & get_a() const
Definition ec_group.cpp:518
const BigInt & get_g_y() const
Definition ec_group.cpp:570
const BigInt & get_g_x() const
Definition ec_group.cpp:566
size_t get_p_bytes() const
Definition ec_group.cpp:502
const BigInt & private_value() const
Definition ecc_key.cpp:117
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition ecc_key.cpp:200
const EC_Group & domain() const
Definition ecc_key.cpp:63
const EC_AffinePoint & _public_ec_point() const
Definition ecc_key.cpp:75
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:298
std::unique_ptr< Public_Key > public_key() const override
Definition sm2.cpp:23
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition sm2.cpp:264
bool check_key(RandomNumberGenerator &rng, bool) const override
Definition sm2.cpp:27
SM2_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition sm2.cpp:48
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
Definition sm2.cpp:253
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const final
Definition sm2.cpp:249
std::string algo_name() const override
Definition sm2.cpp:19
int(* update)(CTX *, const void *, CC_LONG len)
int(* final)(unsigned char *, CTX *)
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:75
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61
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:68