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