aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/pubkey/sm2/sm2_enc.cpp
blob: aca31941d2a65fa3a393e5b31c3f178a611c1a9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
* SM2 Encryption
* (C) 2017 Ribose Inc
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/sm2_enc.h>
#include <botan/pk_ops.h>
#include <botan/keypair.h>
#include <botan/kdf.h>
#include <botan/hash.h>

namespace Botan {

bool SM2_Encryption_PrivateKey::check_key(RandomNumberGenerator& rng,
                                         bool strong) const
   {
   if(!public_point().on_the_curve())
      return false;

   if(!strong)
      return true;

   return KeyPair::encryption_consistency_check(rng, *this, "SM3");
   }

SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(const AlgorithmIdentifier& alg_id,
                                                     const secure_vector<uint8_t>& key_bits) :
   EC_PrivateKey(alg_id, key_bits)
   {
   }

SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(RandomNumberGenerator& rng,
                                                     const EC_Group& domain,
                                                     const BigInt& x) :
   EC_PrivateKey(rng, domain, x)
   {
   }

namespace {

class SM2_Encryption_Operation : public PK_Ops::Encryption
   {
   public:
      SM2_Encryption_Operation(const SM2_Encryption_PublicKey& key, const std::string& kdf_hash) :
         m_p_bytes(key.domain().get_curve().get_p().bytes()),
         m_order(key.domain().get_order()),
         m_base_point(key.domain().get_base_point(), m_order),
         m_public_point(key.public_point(), m_order),
         m_kdf_hash(kdf_hash)
         {}

      size_t max_input_bits() const override
         {
         // This is arbitrary, but assumes SM2 is used for key encapsulation
         return 512;
         }

      secure_vector<uint8_t> encrypt(const uint8_t msg[],
                                     size_t msg_len,
                                     RandomNumberGenerator& rng) override
         {
         std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
         std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");

         secure_vector<uint8_t> ciphertext;
         ciphertext.reserve(1 + m_p_bytes*2 + msg_len + hash->output_length());

         const BigInt k = BigInt::random_integer(rng, 1, m_order);

         const PointGFp C1 = m_base_point.blinded_multiply(k, rng);
         const BigInt x1 = C1.get_affine_x();
         const BigInt y1 = C1.get_affine_y();
         std::vector<uint8_t> x1_bytes(m_p_bytes);
         std::vector<uint8_t> y1_bytes(m_p_bytes);
         BigInt::encode_1363(x1_bytes.data(), x1_bytes.size(), x1);
         BigInt::encode_1363(y1_bytes.data(), y1_bytes.size(), y1);

         const PointGFp kPB = m_public_point.blinded_multiply(k, rng);

         const BigInt x2 = kPB.get_affine_x();
         const BigInt y2 = kPB.get_affine_y();
         std::vector<uint8_t> x2_bytes(m_p_bytes);
         std::vector<uint8_t> y2_bytes(m_p_bytes);
         BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
         BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);

         secure_vector<uint8_t> kdf_input;
         kdf_input += x2_bytes;
         kdf_input += y2_bytes;

         const secure_vector<uint8_t> kdf_output =
            kdf->derive_key(msg_len, kdf_input.data(), kdf_input.size());

         secure_vector<uint8_t> masked_msg(msg_len);
         xor_buf(masked_msg.data(), msg, kdf_output.data(), msg_len);

         hash->update(x2_bytes);
         hash->update(msg, msg_len);
         hash->update(y2_bytes);
         std::vector<uint8_t> C3(hash->output_length());
         hash->final(C3.data());

         ciphertext.push_back(0x04);
         ciphertext += x1_bytes;
         ciphertext += y1_bytes;
         ciphertext += C3;
         ciphertext += masked_msg;

         return ciphertext;
         }

   private:
      size_t m_p_bytes;
      const BigInt& m_order;
      Blinded_Point_Multiply m_base_point;
      Blinded_Point_Multiply m_public_point;
      const std::string m_kdf_hash;
   };

class SM2_Decryption_Operation : public PK_Ops::Decryption
   {
   public:
      SM2_Decryption_Operation(const SM2_Encryption_PrivateKey& key,
                               RandomNumberGenerator& rng,
                               const std::string& kdf_hash) :
         m_key(key),
         m_rng(rng),
         m_kdf_hash(kdf_hash)
         {}

      secure_vector<uint8_t> decrypt(uint8_t& valid_mask,
                                     const uint8_t ciphertext[],
                                     size_t ciphertext_len) override
         {
         const BigInt& cofactor = m_key.domain().get_cofactor();
         const size_t p_bytes = m_key.domain().get_curve().get_p().bytes();

         valid_mask = 0;

         std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
         std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");

         // Too short to be valid - no timing problem from early return
         if(ciphertext_len < 1 + p_bytes*2 + hash->output_length())
            {
            return secure_vector<uint8_t>();
            }

         if(ciphertext[0] != 0x04)
            {
            return secure_vector<uint8_t>();
            }

         const size_t msg_len = ciphertext_len - (1 + p_bytes*2 + hash->output_length());

         const PointGFp C1 = OS2ECP(ciphertext, 1 + p_bytes*2, m_key.domain().get_curve());
         // OS2ECP verifies C1 is on the curve

         Blinded_Point_Multiply C1_mul(C1, m_key.domain().get_order());

         if(cofactor > 1 && C1_mul.blinded_multiply(cofactor, m_rng).is_zero())
            {
            return secure_vector<uint8_t>();
            }

         const PointGFp dbC1 = C1_mul.blinded_multiply(m_key.private_value(), m_rng);

         const BigInt x2 = dbC1.get_affine_x();
         const BigInt y2 = dbC1.get_affine_y();

         std::vector<uint8_t> x2_bytes(p_bytes);
         std::vector<uint8_t> y2_bytes(p_bytes);
         BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
         BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);

         secure_vector<uint8_t> kdf_input;
         kdf_input += x2_bytes;
         kdf_input += y2_bytes;

         const secure_vector<uint8_t> kdf_output =
            kdf->derive_key(msg_len, kdf_input.data(), kdf_input.size());

         secure_vector<uint8_t> msg(msg_len);
         xor_buf(msg.data(), ciphertext + (1+p_bytes*2+hash->output_length()), kdf_output.data(), msg_len);

         hash->update(x2_bytes);
         hash->update(msg);
         hash->update(y2_bytes);
         secure_vector<uint8_t> u = hash->final();

         if(constant_time_compare(u.data(), ciphertext + (1+p_bytes*2), hash->output_length()) == false)
            return secure_vector<uint8_t>();

         valid_mask = 0xFF;
         return msg;
         }
   private:
      const SM2_Encryption_PrivateKey& m_key;
      RandomNumberGenerator& m_rng;
      const std::string m_kdf_hash;
   };

}

std::unique_ptr<PK_Ops::Encryption>
SM2_Encryption_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
                                               const std::string& params,
                                               const std::string& provider) const
   {
   if(provider == "base" || provider.empty())
      {
      const std::string kdf_hash = (params.empty() ? "SM3" : params);
      return std::unique_ptr<PK_Ops::Encryption>(new SM2_Encryption_Operation(*this, kdf_hash));
      }

   throw Provider_Not_Found(algo_name(), provider);
   }

std::unique_ptr<PK_Ops::Decryption>
SM2_Encryption_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
                                                const std::string& params,
                                                const std::string& provider) const
   {
   if(provider == "base" || provider.empty())
      {
      const std::string kdf_hash = (params.empty() ? "SM3" : params);
      return std::unique_ptr<PK_Ops::Decryption>(new SM2_Decryption_Operation(*this, rng, kdf_hash));
      }

   throw Provider_Not_Found(algo_name(), provider);
   }

}