Botan 3.14.1
Crypto and TLS for C&
sm2_enc.cpp
Go to the documentation of this file.
1/*
2* SM2 Encryption
3* (C) 2017 Ribose Inc
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/sm2.h>
9
10#include <botan/ber_dec.h>
11#include <botan/der_enc.h>
12#include <botan/ec_group.h>
13#include <botan/hash.h>
14#include <botan/kdf.h>
15#include <botan/mem_ops.h>
16#include <botan/pk_ops.h>
17#include <botan/pk_options_readers.h>
18#include <botan/internal/ct_utils.h>
19#include <botan/internal/fmt.h>
20#include <botan/internal/pk_options_impl.h>
21
22namespace Botan {
23
24namespace {
25
26class SM2_Encryption_Operation final : public PK_Ops::Encryption {
27 public:
28 SM2_Encryption_Operation(const SM2_Encryption_PublicKey& key, std::string_view kdf_hash) :
29 m_group(key.domain()), m_peer(key.public_ec_point()) {
30 m_hash = HashFunction::create_or_throw(kdf_hash);
31 m_kdf = KDF::create_or_throw(fmt("KDF2({})", kdf_hash));
32 }
33
34 size_t max_input_bits() const override {
35 // This is arbitrary, but assumes SM2 is used for key encapsulation
36 return 512;
37 }
38
39 size_t ciphertext_length(size_t ptext_len) const override {
40 const size_t elem_size = m_group.get_order_bytes();
41 const size_t der_overhead = 16;
42
43 return der_overhead + 2 * elem_size + m_hash->output_length() + ptext_len;
44 }
45
46 std::vector<uint8_t> encrypt(std::span<const uint8_t> msg, RandomNumberGenerator& rng) override {
47 const auto scope = CT::scoped_poison(msg);
48
49 for(;;) {
50 const auto k = EC_Scalar::random(m_group, rng);
51 CT::poison(k);
52
53 const EC_AffinePoint C1 = EC_AffinePoint::g_mul(k, rng);
54 CT::unpoison(C1);
55
56 const EC_AffinePoint kPB = m_peer.mul(k, rng);
57
58 const auto x2_bytes = kPB.x_bytes();
59 const auto y2_bytes = kPB.y_bytes();
60
61 secure_vector<uint8_t> kdf_input;
62 kdf_input += x2_bytes;
63 kdf_input += y2_bytes;
64
65 const auto kdf_output = m_kdf->derive_key(msg.size(), kdf_input);
66
67 /*
68 * According to GB/T 32918.4-2016 section 6.1 we must retry if the
69 * KDF output is the all-zero string.
70 */
71 if(!msg.empty() && CT::all_zeros(kdf_output.data(), kdf_output.size()).as_bool()) {
72 continue;
73 }
74
75 std::vector<uint8_t> masked_msg(msg.size());
76 xor_buf(masked_msg, msg, kdf_output);
77
78 m_hash->update(x2_bytes);
79 m_hash->update(msg);
80 m_hash->update(y2_bytes);
81 const auto C3 = m_hash->final<std::vector<uint8_t>>();
82
83 CT::unpoison_all(masked_msg, C3);
84
85 std::vector<uint8_t> ctext;
86 DER_Encoder(ctext)
87 .start_sequence()
88 .encode(BigInt(C1.x_bytes()))
89 .encode(BigInt(C1.y_bytes()))
90 .encode(C3, ASN1_Type::OctetString)
91 .encode(masked_msg, ASN1_Type::OctetString)
92 .end_cons();
93
94 return ctext;
95 }
96 }
97
98 private:
99 const EC_Group m_group;
100 const EC_AffinePoint m_peer;
101 std::unique_ptr<HashFunction> m_hash;
102 std::unique_ptr<KDF> m_kdf;
103};
104
105class SM2_Decryption_Operation final : public PK_Ops::Decryption {
106 public:
107 SM2_Decryption_Operation(const SM2_Encryption_PrivateKey& key,
108 RandomNumberGenerator& rng,
109 std::string_view kdf_hash) :
110 m_group(key.domain()), m_x(key._private_key()), m_rng(rng) {
111 m_hash = HashFunction::create_or_throw(kdf_hash);
112
113 const std::string kdf_name = fmt("KDF2({})", kdf_hash);
114 m_kdf = KDF::create_or_throw(kdf_name);
115 }
116
117 size_t plaintext_length(size_t ptext_len) const override {
118 /*
119 * This ignores the DER encoding and so overestimates the
120 * plaintext length by 12 bytes or so
121 */
122 const size_t elem_size = m_group.get_order_bytes();
123
124 if(ptext_len < 2 * elem_size + m_hash->output_length()) {
125 return 0;
126 }
127
128 return ptext_len - (2 * elem_size + m_hash->output_length());
129 }
130
131 size_t ciphertext_length(size_t ptext_len) const override {
132 const size_t elem_size = m_group.get_order_bytes();
133 const size_t der_overhead = 16;
134
135 return der_overhead + 2 * elem_size + m_hash->output_length() + ptext_len;
136 }
137
138 size_t decrypt(uint8_t& valid_mask, std::span<uint8_t> ptext, std::span<const uint8_t> ctext) override {
139 const size_t p_bytes = m_group.get_p_bytes();
140
141 valid_mask = 0x00;
142
143 // Too short to be valid - no timing problem from early return
144 if(ctext.size() < 1 + p_bytes * 2 + m_hash->output_length()) {
145 return 0;
146 }
147
148 BigInt x1;
149 BigInt y1;
151 secure_vector<uint8_t> masked_msg;
152
153 BER_Decoder(ctext, BER_Decoder::Limits::DER())
154 .start_sequence()
155 .decode(x1)
156 .decode(y1)
157 .decode(C3, ASN1_Type::OctetString)
158 .decode(masked_msg, ASN1_Type::OctetString)
159 .end_cons()
160 .verify_end();
161
162 // Wrong length so certainly invalid, reject immediately
163 if(C3.size() != m_hash->output_length()) {
164 return 0;
165 }
166
167 // Longer than any output of encryption (see plaintext_length), so also invalid
168 if(masked_msg.size() > ptext.size()) {
169 return 0;
170 }
171
172 auto C1 = EC_AffinePoint::from_bigint_xy(m_group, x1, y1);
173
174 // Here C1 is publicly invalid, so no problem with early return:
175 if(!C1) {
176 return 0;
177 }
178
179 const auto scope = CT::scoped_poison(m_x);
180
181 const auto dbC1 = C1->mul(m_x, m_rng);
182 const auto x2_bytes = dbC1.x_bytes();
183 const auto y2_bytes = dbC1.y_bytes();
184
185 const auto kdf_output = m_kdf->derive_key(masked_msg.size(), dbC1.xy_bytes());
186
187 /*
188 * GB/T 32918.4-2016 section 7.1 requires we reject a message which
189 * results in a KDF output which is the all-zero string.
190 */
191 const auto kdf_nonzero =
192 masked_msg.empty() ? CT::Mask<uint8_t>::set() : ~CT::all_zeros(kdf_output.data(), kdf_output.size());
193
194 xor_buf(masked_msg.data(), kdf_output.data(), kdf_output.size());
195
196 m_hash->update(x2_bytes);
197 m_hash->update(masked_msg);
198 m_hash->update(y2_bytes);
199 const auto u = m_hash->final();
200
201 const auto mac_ok = CT::is_equal<uint8_t>(u, C3) & kdf_nonzero;
202 valid_mask = mac_ok.if_set_return(0xFF);
203
204 // Zero the plaintext if the MAC check failed
205 (~mac_ok).if_set_zero_out(masked_msg.data(), masked_msg.size());
206 copy_mem(ptext.first(masked_msg.size()), masked_msg);
207 return CT::Mask<size_t>::expand(mac_ok).if_set_return(masked_msg.size());
208 }
209
210 private:
211 const EC_Group m_group;
212 const EC_Scalar m_x;
213 RandomNumberGenerator& m_rng;
214 std::unique_ptr<HashFunction> m_hash;
215 std::unique_ptr<KDF> m_kdf;
216};
217
218} // namespace
219
220std::unique_ptr<PK_Ops::Encryption> SM2_PublicKey::_create_encryption_op(
221 RandomNumberGenerator& rng, const PK_Encryption_Options_Reader& options) const {
222 BOTAN_UNUSED(rng);
223
225
226 // SM3 is the only hash specified for use with SM2, so it is the default
227 return std::make_unique<SM2_Encryption_Operation>(*this, options.hash_function().value_or("SM3"));
228}
229
230std::unique_ptr<PK_Ops::Decryption> SM2_PrivateKey::_create_decryption_op(
231 RandomNumberGenerator& rng, const PK_Encryption_Options_Reader& options) const {
233
234 return std::make_unique<SM2_Decryption_Operation>(*this, rng, options.hash_function().value_or("SM3"));
235}
236
237} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:151
static Limits DER()
Definition ber_dec.h:44
static constexpr Mask< T > set()
Definition ct_utils.h:387
static constexpr Mask< T > expand(T v)
Definition ct_utils.h:397
static std::optional< EC_AffinePoint > from_bigint_xy(const EC_Group &group, const BigInt &x, const BigInt &y)
Definition ec_apoint.cpp:93
static EC_AffinePoint g_mul(const EC_Scalar &scalar, RandomNumberGenerator &rng)
Multiply by the group generator returning a complete point.
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
static std::unique_ptr< KDF > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition kdf.cpp:208
const std::optional< std::string > & hash_function() const
std::unique_ptr< PK_Ops::Decryption > _create_decryption_op(RandomNumberGenerator &rng, const PK_Encryption_Options_Reader &options) const override
Definition sm2_enc.cpp:230
std::unique_ptr< PK_Ops::Encryption > _create_encryption_op(RandomNumberGenerator &rng, const PK_Encryption_Options_Reader &options) const override
Definition sm2_enc.cpp:220
std::string algo_name() const override
Definition sm2.cpp:24
constexpr auto scoped_poison(const Ts &... xs)
Definition ct_utils.h:222
constexpr CT::Mask< T > is_equal(const T x[], const T y[], size_t len)
Definition ct_utils.h:803
constexpr void unpoison_all(const Ts &... ts)
Definition ct_utils.h:207
constexpr void unpoison(const T *p, size_t n)
Definition ct_utils.h:67
constexpr CT::Mask< T > all_zeros(const T elem[], size_t len)
Definition ct_utils.h:790
constexpr void poison(const T *p, size_t n)
Definition ct_utils.h:56
std::string decrypt(std::span< const uint8_t > input, std::string_view passphrase)
std::string encrypt(const uint8_t input[], size_t input_len, std::string_view passphrase, RandomNumberGenerator &rng)
Definition cryptobox.cpp:44
SM2_PublicKey SM2_Encryption_PublicKey
Definition sm2.h:157
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
void require_software_provider(const OptionsT &options, std::string_view algo_name)
SM2_PrivateKey SM2_Encryption_PrivateKey
Definition sm2.h:160
constexpr void xor_buf(ranges::contiguous_output_range< uint8_t > auto &&out, ranges::contiguous_range< uint8_t > auto &&in)
Definition mem_ops.h:403
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128