Botan  2.8.0
Crypto and TLS for C++11
ecies.cpp
Go to the documentation of this file.
1 /*
2 * ECIES
3 * (C) 2016 Philipp Weber
4 * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8 
9 #include <botan/ecies.h>
10 #include <botan/numthry.h>
11 #include <botan/cipher_mode.h>
12 #include <botan/mac.h>
13 
14 #include <botan/internal/ct_utils.h>
15 #include <botan/internal/pk_ops_impl.h>
16 
17 namespace Botan {
18 
19 namespace {
20 
21 /**
22 * Private key type for ECIES_ECDH_KA_Operation
23 */
24 class ECIES_PrivateKey final : public EC_PrivateKey, public PK_Key_Agreement_Key
25  {
26  public:
27  explicit ECIES_PrivateKey(const ECDH_PrivateKey& private_key) :
28  EC_PublicKey(private_key),
29  EC_PrivateKey(private_key),
30  PK_Key_Agreement_Key(),
31  m_key(private_key)
32  {
33  }
34 
35  std::vector<uint8_t> public_value() const override
36  {
37  return m_key.public_value();
38  }
39 
40  std::string algo_name() const override
41  {
42  return "ECIES";
43  }
44 
45  std::unique_ptr<PK_Ops::Key_Agreement>
46  create_key_agreement_op(RandomNumberGenerator& rng,
47  const std::string& params,
48  const std::string& provider) const override;
49 
50  private:
51  ECDH_PrivateKey m_key;
52  };
53 
54 /**
55 * Implements ECDH key agreement without using the cofactor mode
56 */
57 class ECIES_ECDH_KA_Operation final : public PK_Ops::Key_Agreement_with_KDF
58  {
59  public:
60  ECIES_ECDH_KA_Operation(const ECIES_PrivateKey& private_key, RandomNumberGenerator& rng) :
61  PK_Ops::Key_Agreement_with_KDF("Raw"),
62  m_key(private_key),
63  m_rng(rng)
64  {
65  }
66 
67  size_t agreed_value_size() const override { return m_key.domain().get_p_bytes(); }
68 
69  secure_vector<uint8_t> raw_agree(const uint8_t w[], size_t w_len) override
70  {
71  const EC_Group& group = m_key.domain();
72 
73  PointGFp input_point = group.OS2ECP(w, w_len);
74  input_point.randomize_repr(m_rng);
75 
76  const PointGFp S = group.blinded_var_point_multiply(
77  input_point, m_key.private_value(), m_rng, m_ws);
78 
79  if(S.on_the_curve() == false)
80  throw Internal_Error("ECDH agreed value was not on the curve");
81  return BigInt::encode_1363(S.get_affine_x(), group.get_p_bytes());
82  }
83 
84  private:
85  ECIES_PrivateKey m_key;
86  RandomNumberGenerator& m_rng;
87  std::vector<BigInt> m_ws;
88  };
89 
90 std::unique_ptr<PK_Ops::Key_Agreement>
91 ECIES_PrivateKey::create_key_agreement_op(RandomNumberGenerator& rng,
92  const std::string& /*params*/,
93  const std::string& /*provider*/) const
94  {
95  return std::unique_ptr<PK_Ops::Key_Agreement>(new ECIES_ECDH_KA_Operation(*this, rng));
96  }
97 
98 /**
99 * Creates a PK_Key_Agreement instance for the given key and ecies_params
100 * Returns either ECIES_ECDH_KA_Operation or the default implementation for the given key,
101 * depending on the key and ecies_params
102 * @param private_key the private key used for the key agreement
103 * @param ecies_params settings for ecies
104 * @param for_encryption disable cofactor mode if the secret will be used for encryption
105 * (according to ISO 18033 cofactor mode is only used during decryption)
106 */
107 PK_Key_Agreement create_key_agreement(const PK_Key_Agreement_Key& private_key,
108  const ECIES_KA_Params& ecies_params,
109  bool for_encryption,
110  RandomNumberGenerator& rng)
111  {
112  const ECDH_PrivateKey* ecdh_key = dynamic_cast<const ECDH_PrivateKey*>(&private_key);
113 
114  if(ecdh_key == nullptr && (ecies_params.cofactor_mode() || ecies_params.old_cofactor_mode()
115  || ecies_params.check_mode()))
116  {
117  // assume we have a private key from an external provider (e.g. pkcs#11):
118  // there is no way to determine or control whether the provider uses cofactor mode or not.
119  // ISO 18033 does not allow cofactor mode in combination with old cofactor mode or check mode
120  // => disable cofactor mode, old cofactor mode and check mode for unknown keys/providers (as a precaution).
121  throw Invalid_Argument("ECIES: cofactor, old cofactor and check mode are only supported for ECDH_PrivateKey");
122  }
123 
124  if(ecdh_key && (for_encryption || !ecies_params.cofactor_mode()))
125  {
126  // ECDH_KA_Operation uses cofactor mode: use own key agreement method if cofactor should not be used.
127  return PK_Key_Agreement(ECIES_PrivateKey(*ecdh_key), rng, "Raw");
128  }
129 
130  return PK_Key_Agreement(private_key, rng, "Raw"); // use default implementation
131  }
132 }
133 
135  const ECIES_KA_Params& ecies_params,
136  bool for_encryption,
137  RandomNumberGenerator& rng) :
138  m_ka(create_key_agreement(private_key, ecies_params, for_encryption, rng)),
139  m_params(ecies_params)
140  {
141  }
142 
143 /**
144 * ECIES secret derivation according to ISO 18033-2
145 */
146 SymmetricKey ECIES_KA_Operation::derive_secret(const std::vector<uint8_t>& eph_public_key_bin,
147  const PointGFp& other_public_key_point) const
148  {
149  if(other_public_key_point.is_zero())
150  {
151  throw Invalid_Argument("ECIES: other public key point is zero");
152  }
153 
154  std::unique_ptr<KDF> kdf = Botan::KDF::create_or_throw(m_params.kdf_spec());
155 
156  PointGFp other_point = other_public_key_point;
157 
158  // ISO 18033: step b
159  if(m_params.old_cofactor_mode())
160  {
161  other_point *= m_params.domain().get_cofactor();
162  }
163 
164  secure_vector<uint8_t> derivation_input;
165 
166  // ISO 18033: encryption step e / decryption step g
167  if(!m_params.single_hash_mode())
168  {
169  derivation_input += eph_public_key_bin;
170  }
171 
172  // ISO 18033: encryption step f / decryption step h
173  std::vector<uint8_t> other_public_key_bin = other_point.encode(m_params.compression_type());
174  // Note: the argument `m_params.secret_length()` passed for `key_len` will only be used by providers because
175  // "Raw" is passed to the `PK_Key_Agreement` if the implementation of botan is used.
176  const SymmetricKey peh = m_ka.derive_key(m_params.domain().get_order().bytes(), other_public_key_bin.data(), other_public_key_bin.size());
177  derivation_input.insert(derivation_input.end(), peh.begin(), peh.end());
178 
179  // ISO 18033: encryption step g / decryption step i
180  return kdf->derive_key(m_params.secret_length(), derivation_input);
181  }
182 
183 
184 ECIES_KA_Params::ECIES_KA_Params(const EC_Group& domain, const std::string& kdf_spec, size_t length,
185  PointGFp::Compression_Type compression_type, ECIES_Flags flags) :
186  m_domain(domain),
187  m_kdf_spec(kdf_spec),
188  m_length(length),
189  m_compression_mode(compression_type),
190  m_flags(flags)
191  {
192  }
193 
194 ECIES_System_Params::ECIES_System_Params(const EC_Group& domain, const std::string& kdf_spec,
195  const std::string& dem_algo_spec, size_t dem_key_len,
196  const std::string& mac_spec, size_t mac_key_len,
197  PointGFp::Compression_Type compression_type, ECIES_Flags flags) :
198  ECIES_KA_Params(domain, kdf_spec, dem_key_len + mac_key_len, compression_type, flags),
199  m_dem_spec(dem_algo_spec),
200  m_dem_keylen(dem_key_len),
201  m_mac_spec(mac_spec),
202  m_mac_keylen(mac_key_len)
203  {
204  // ISO 18033: "At most one of CofactorMode, OldCofactorMode, and CheckMode may be 1."
205  if(size_t(cofactor_mode()) + size_t(old_cofactor_mode()) + size_t(check_mode()) > 1)
206  {
207  throw Invalid_Argument("ECIES: only one of cofactor_mode, old_cofactor_mode and check_mode can be set");
208  }
209  }
210 
211 ECIES_System_Params::ECIES_System_Params(const EC_Group& domain, const std::string& kdf_spec,
212  const std::string& dem_algo_spec, size_t dem_key_len,
213  const std::string& mac_spec, size_t mac_key_len) :
214  ECIES_System_Params(domain, kdf_spec, dem_algo_spec, dem_key_len, mac_spec, mac_key_len, PointGFp::UNCOMPRESSED,
215  ECIES_Flags::NONE)
216  {
217  }
218 
219 std::unique_ptr<MessageAuthenticationCode> ECIES_System_Params::create_mac() const
220  {
222  }
223 
224 std::unique_ptr<Cipher_Mode> ECIES_System_Params::create_cipher(Botan::Cipher_Dir direction) const
225  {
226  return Cipher_Mode::create_or_throw(m_dem_spec, direction);
227  }
228 
229 
230 /*
231 * ECIES_Encryptor Constructor
232 */
234  const ECIES_System_Params& ecies_params,
235  RandomNumberGenerator& rng) :
236  m_ka(private_key, ecies_params, true, rng),
237  m_params(ecies_params),
238  m_eph_public_key_bin(private_key.public_value()), // returns the uncompressed public key, see conversion below
239  m_iv(),
240  m_other_point(),
241  m_label()
242  {
243  if(ecies_params.compression_type() != PointGFp::UNCOMPRESSED)
244  {
245  // ISO 18033: step d
246  // convert only if necessary; m_eph_public_key_bin has been initialized with the uncompressed format
247  m_eph_public_key_bin = m_params.domain().OS2ECP(m_eph_public_key_bin).encode(ecies_params.compression_type());
248  }
249  m_mac = m_params.create_mac();
250  m_cipher = m_params.create_cipher(ENCRYPTION);
251  }
252 
253 /*
254 * ECIES_Encryptor Constructor
255 */
257  ECIES_Encryptor(ECDH_PrivateKey(rng, ecies_params.domain()), ecies_params, rng)
258  {
259  }
260 
261 size_t ECIES_Encryptor::maximum_input_size() const
262  {
263  /*
264  ECIES should just be used for key transport so this (arbitrary) limit
265  seems sufficient
266  */
267  return 64;
268  }
269 
270 size_t ECIES_Encryptor::ciphertext_length(size_t ptext_len) const
271  {
272  return m_eph_public_key_bin.size() +
273  m_mac->output_length() +
274  m_cipher->output_length(ptext_len);
275  }
276 
277 /*
278 * ECIES Encryption according to ISO 18033-2
279 */
280 std::vector<uint8_t> ECIES_Encryptor::enc(const uint8_t data[], size_t length, RandomNumberGenerator&) const
281  {
282  if(m_other_point.is_zero())
283  {
284  throw Invalid_State("ECIES: the other key is zero");
285  }
286 
287  const SymmetricKey secret_key = m_ka.derive_secret(m_eph_public_key_bin, m_other_point);
288 
289  // encryption
290 
291  m_cipher->set_key(SymmetricKey(secret_key.begin(), m_params.dem_keylen()));
292  if(m_iv.size() != 0)
293  {
294  m_cipher->start(m_iv.bits_of());
295  }
296  secure_vector<uint8_t> encrypted_data(data, data + length);
297  m_cipher->finish(encrypted_data);
298 
299  // concat elements
300 
301  std::vector<uint8_t> out(m_eph_public_key_bin.size() + encrypted_data.size() + m_mac->output_length());
302  buffer_insert(out, 0, m_eph_public_key_bin);
303  buffer_insert(out, m_eph_public_key_bin.size(), encrypted_data);
304 
305  // mac
306  m_mac->set_key(secret_key.begin() + m_params.dem_keylen(), m_params.mac_keylen());
307  m_mac->update(encrypted_data);
308  if(!m_label.empty())
309  {
310  m_mac->update(m_label);
311  }
312  m_mac->final(out.data() + m_eph_public_key_bin.size() + encrypted_data.size());
313 
314  return out;
315  }
316 
317 
319  const ECIES_System_Params& ecies_params,
320  RandomNumberGenerator& rng) :
321  m_ka(key, ecies_params, false, rng),
322  m_params(ecies_params),
323  m_iv(),
324  m_label()
325  {
326  // ISO 18033: "If v > 1 and CheckMode = 0, then we must have gcd(u, v) = 1." (v = index, u= order)
327  if(!ecies_params.check_mode())
328  {
329  const Botan::BigInt& cofactor = m_params.domain().get_cofactor();
330  if(cofactor > 1 && Botan::gcd(cofactor, m_params.domain().get_order()) != 1)
331  {
332  throw Invalid_Argument("ECIES: gcd of cofactor and order must be 1 if check_mode is 0");
333  }
334  }
335 
336  m_mac = m_params.create_mac();
337  m_cipher = m_params.create_cipher(DECRYPTION);
338  }
339 
340 size_t ECIES_Decryptor::plaintext_length(size_t ctext_len) const
341  {
342  const size_t point_size = m_params.domain().point_size(m_params.compression_type());
343  const size_t overhead = point_size + m_mac->output_length();
344 
345  if(ctext_len < overhead)
346  return 0;
347 
348  return m_cipher->output_length(ctext_len - overhead);
349  }
350 
351 /**
352 * ECIES Decryption according to ISO 18033-2
353 */
354 secure_vector<uint8_t> ECIES_Decryptor::do_decrypt(uint8_t& valid_mask, const uint8_t in[], size_t in_len) const
355  {
356  const size_t point_size = m_params.domain().point_size(m_params.compression_type());
357 
358  if(in_len < point_size + m_mac->output_length())
359  {
360  throw Decoding_Error("ECIES decryption: ciphertext is too short");
361  }
362 
363  // extract data
364  const std::vector<uint8_t> other_public_key_bin(in, in + point_size); // the received (ephemeral) public key
365  const std::vector<uint8_t> encrypted_data(in + point_size, in + in_len - m_mac->output_length());
366  const std::vector<uint8_t> mac_data(in + in_len - m_mac->output_length(), in + in_len);
367 
368  // ISO 18033: step a
369  PointGFp other_public_key = m_params.domain().OS2ECP(other_public_key_bin);
370 
371  // ISO 18033: step b
372  if(m_params.check_mode() && !other_public_key.on_the_curve())
373  {
374  throw Decoding_Error("ECIES decryption: received public key is not on the curve");
375  }
376 
377  // ISO 18033: step e (and step f because get_affine_x (called by ECDH_KA_Operation::raw_agree)
378  // throws Illegal_Transformation if the point is zero)
379  const SymmetricKey secret_key = m_ka.derive_secret(other_public_key_bin, other_public_key);
380 
381  // validate mac
382  m_mac->set_key(secret_key.begin() + m_params.dem_keylen(), m_params.mac_keylen());
383  m_mac->update(encrypted_data);
384  if(!m_label.empty())
385  {
386  m_mac->update(m_label);
387  }
388  const secure_vector<uint8_t> calculated_mac = m_mac->final();
389  valid_mask = CT::expand_mask<uint8_t>(constant_time_compare(mac_data.data(), calculated_mac.data(), mac_data.size()));
390 
391  if(valid_mask)
392  {
393  // decrypt data
394 
395  m_cipher->set_key(SymmetricKey(secret_key.begin(), m_params.dem_keylen()));
396  if(m_iv.size() != 0)
397  {
398  m_cipher->start(m_iv.bits_of());
399  }
400 
401  try
402  {
403  // the decryption can fail:
404  // e.g. Integrity_Failure is thrown if GCM is used and the message does not have a valid tag
405  secure_vector<uint8_t> decrypted_data(encrypted_data.begin(), encrypted_data.end());
406  m_cipher->finish(decrypted_data);
407  return decrypted_data;
408  }
409  catch(...)
410  {
411  valid_mask = 0;
412  }
413  }
414  return secure_vector<uint8_t>();
415  }
416 
417 }
std::unique_ptr< MessageAuthenticationCode > create_mac() const
creates an instance of the message authentication code
Definition: ecies.cpp:219
ECIES_KA_Params(const EC_Group &domain, const std::string &kdf_spec, size_t length, PointGFp::Compression_Type compression_type, ECIES_Flags flags)
Definition: ecies.cpp:184
SymmetricKey derive_secret(const std::vector< uint8_t > &eph_public_key_bin, const PointGFp &other_public_key_point) const
Definition: ecies.cpp:146
BigInt gcd(const BigInt &a, const BigInt &b)
Definition: numthry.cpp:51
const BigInt & get_order() const
Definition: ec_group.cpp:479
ECIES_Flags
Definition: ecies.h:27
size_t size() const
Definition: symkey.h:26
std::vector< uint8_t > encode(PointGFp::Compression_Type format) const
Definition: point_gfp.cpp:597
bool check_mode() const
Definition: ecies.h:99
static std::vector< uint8_t > encode(const BigInt &n)
Definition: bigint.h:678
PointGFp::Compression_Type compression_type() const
Definition: ecies.h:104
int(* final)(unsigned char *, CTX *)
Flags flags(Flag flags)
Definition: p11.h:858
size_t dem_keylen() const
returns the length of the key used by the data encryption method
Definition: ecies.h:162
bool constant_time_compare(const uint8_t x[], const uint8_t y[], size_t len)
Definition: mem_ops.cpp:51
size_t point_size(PointGFp::Compression_Type format) const
Definition: ec_group.cpp:529
const std::string & kdf_spec() const
Definition: ecies.h:109
ECIES_Encryptor(const PK_Key_Agreement_Key &private_key, const ECIES_System_Params &ecies_params, RandomNumberGenerator &rng)
Definition: ecies.cpp:233
ECIES_KA_Operation(const PK_Key_Agreement_Key &private_key, const ECIES_KA_Params &ecies_params, bool for_encryption, RandomNumberGenerator &rng)
Definition: ecies.cpp:134
bool single_hash_mode() const
Definition: ecies.h:84
bool cofactor_mode() const
Definition: ecies.h:89
ECIES_System_Params(const EC_Group &domain, const std::string &kdf_spec, const std::string &dem_algo_spec, size_t dem_key_len, const std::string &mac_spec, size_t mac_key_len)
Definition: ecies.cpp:211
size_t mac_keylen() const
returns the length of the key used by the message authentication code
Definition: ecies.h:168
const BigInt & get_cofactor() const
Definition: ec_group.cpp:494
PointGFp OS2ECP(const uint8_t bits[], size_t len) const
Definition: ec_group.cpp:538
SymmetricKey derive_key(size_t key_len, const uint8_t in[], size_t in_len, const uint8_t params[], size_t params_len) const
Definition: pubkey.cpp:218
const uint8_t * end() const
Definition: symkey.h:41
Definition: alg_id.cpp:13
std::unique_ptr< Cipher_Mode > create_cipher(Botan::Cipher_Dir direction) const
creates an instance of the data encryption method
Definition: ecies.cpp:224
OctetString SymmetricKey
Definition: symkey.h:136
size_t bytes() const
Definition: bigint.cpp:221
const uint8_t * begin() const
Definition: symkey.h:36
bool old_cofactor_mode() const
Definition: ecies.h:94
const EC_Group & domain() const
Definition: ecies.h:74
Cipher_Dir
Definition: cipher_mode.h:23
ECIES_Decryptor(const PK_Key_Agreement_Key &private_key, const ECIES_System_Params &ecies_params, RandomNumberGenerator &rng)
Definition: ecies.cpp:318
size_t buffer_insert(std::vector< T, Alloc > &buf, size_t buf_offset, const T input[], size_t input_length)
Definition: secmem.h:103
static std::unique_ptr< Cipher_Mode > create_or_throw(const std::string &algo, Cipher_Dir direction, const std::string &provider="")
Definition: cipher_mode.cpp:44
bool is_zero() const
Definition: point_gfp.h:180
static std::unique_ptr< MessageAuthenticationCode > create_or_throw(const std::string &algo_spec, const std::string &provider="")
Definition: mac.cpp:141
static secure_vector< uint8_t > encode_1363(const BigInt &n, size_t bytes)
Definition: big_code.cpp:124
std::vector< T, secure_allocator< T > > secure_vector
Definition: secmem.h:88
size_t secret_length() const
Definition: ecies.h:79
secure_vector< uint8_t > bits_of() const
Definition: symkey.h:31
static std::unique_ptr< KDF > create_or_throw(const std::string &algo_spec, const std::string &provider="")
Definition: kdf.cpp:222
const RSA_PrivateKey & m_key
Definition: rsa.cpp:277