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