Botan  2.8.0
Crypto and TLS for C++11
p11_rsa.cpp
Go to the documentation of this file.
1 /*
2 * PKCS#11 RSA
3 * (C) 2016 Daniel Neus, Sirrix AG
4 * (C) 2016 Philipp Weber, Sirrix AG
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8 
9 #include <botan/p11_rsa.h>
10 #include <botan/pk_keys.h>
11 
12 #if defined(BOTAN_HAS_RSA)
13 
14 #include <botan/internal/p11_mechanism.h>
15 #include <botan/pk_ops.h>
16 #include <botan/rng.h>
17 #include <botan/blinding.h>
18 #include <botan/pow_mod.h>
19 
20 namespace Botan {
21 
22 namespace PKCS11 {
23 
24 RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(const BigInt& modulus, const BigInt& pub_exponent)
25  : PublicKeyProperties(KeyType::Rsa), m_modulus(modulus), m_pub_exponent(pub_exponent)
26  {
27  add_binary(AttributeType::Modulus, BigInt::encode(m_modulus));
28  add_binary(AttributeType::PublicExponent, BigInt::encode(m_pub_exponent));
29  }
30 
31 RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits)
32  : PublicKeyProperties(KeyType::Rsa)
33  {
34  add_numeric(AttributeType::ModulusBits, bits);
35  }
36 
37 PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle)
38  : Object(session, handle)
39  {
40  m_n = BigInt::decode(get_attribute_value(AttributeType::Modulus));
41  m_e = BigInt::decode(get_attribute_value(AttributeType::PublicExponent));
42  }
43 
44 PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, const RSA_PublicKeyImportProperties& pubkey_props)
45  : RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()), Object(session, pubkey_props)
46  {}
47 
48 
49 RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(const BigInt& modulus, const BigInt& priv_exponent)
50  : PrivateKeyProperties(KeyType::Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent)
51  {
52  add_binary(AttributeType::Modulus, BigInt::encode(m_modulus));
53  add_binary(AttributeType::PrivateExponent, BigInt::encode(m_priv_exponent));
54  }
55 
56 
57 PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle)
58  : Object(session, handle)
59  {
60  m_n = BigInt::decode(get_attribute_value(AttributeType::Modulus));
61  m_e = BigInt::decode(get_attribute_value(AttributeType::PublicExponent));
62  }
63 
64 PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, const RSA_PrivateKeyImportProperties& priv_key_props)
65  : Object(session, priv_key_props)
66  {
67  m_n = priv_key_props.modulus();
68  m_e = BigInt::decode(get_attribute_value(AttributeType::PublicExponent));
69  }
70 
71 PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, uint32_t bits,
72  const RSA_PrivateKeyGenerationProperties& priv_key_props)
73  : RSA_PublicKey(), Object(session)
74  {
75  RSA_PublicKeyGenerationProperties pub_key_props(bits);
76  pub_key_props.set_encrypt(true);
77  pub_key_props.set_verify(true);
78  pub_key_props.set_token(false); // don't create a persistent public key object
79 
80  ObjectHandle pub_key_handle = CK_INVALID_HANDLE;
81  ObjectHandle priv_key_handle = CK_INVALID_HANDLE;
82  Mechanism mechanism = { static_cast< CK_MECHANISM_TYPE >(MechanismType::RsaPkcsKeyPairGen), nullptr, 0 };
83  session.module()->C_GenerateKeyPair(session.handle(), &mechanism,
84  pub_key_props.data(), pub_key_props.count(), priv_key_props.data(), priv_key_props.count(),
85  &pub_key_handle, &priv_key_handle);
86 
87  this->reset_handle(priv_key_handle);
88 
89  m_n = BigInt::decode(get_attribute_value(AttributeType::Modulus));
90  m_e = BigInt::decode(get_attribute_value(AttributeType::PublicExponent));
91  }
92 
93 RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key() const
94  {
95  auto p = get_attribute_value(AttributeType::Prime1);
96  auto q = get_attribute_value(AttributeType::Prime2);
97  auto e = get_attribute_value(AttributeType::PublicExponent);
98  auto d = get_attribute_value(AttributeType::PrivateExponent);
99  auto n = get_attribute_value(AttributeType::Modulus);
100 
101  return RSA_PrivateKey( BigInt::decode(p)
102  , BigInt::decode(q)
103  , BigInt::decode(e)
104  , BigInt::decode(d)
105  , BigInt::decode(n));
106  }
107 
108 secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits() const
109  {
110  return export_key().private_key_bits();
111  }
112 
113 
114 namespace {
115 // note: multiple-part decryption operations (with C_DecryptUpdate/C_DecryptFinal)
116 // are not supported (PK_Ops::Decryption does not provide an `update` method)
117 class PKCS11_RSA_Decryption_Operation final : public PK_Ops::Decryption
118  {
119  public:
120 
121  PKCS11_RSA_Decryption_Operation(const PKCS11_RSA_PrivateKey& key,
122  const std::string& padding,
123  RandomNumberGenerator& rng)
124  : m_key(key),
125  m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)),
126  m_powermod(m_key.get_e(), m_key.get_n()),
127  m_blinder(m_key.get_n(), rng,
128  [ this ](const BigInt& k) { return m_powermod(k); },
129  [ this ](const BigInt& k) { return inverse_mod(k, m_key.get_n()); })
130  {
131  m_bits = m_key.get_n().bits() - 1;
132  }
133 
134  size_t plaintext_length(size_t) const override { return m_key.get_n().bytes(); }
135 
136  secure_vector<uint8_t> decrypt(uint8_t& valid_mask, const uint8_t ciphertext[], size_t ciphertext_len) override
137  {
138  valid_mask = 0;
139  m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
140 
141  std::vector<uint8_t> encrypted_data(ciphertext, ciphertext + ciphertext_len);
142 
143  // blind for RSA/RAW decryption
144  if(! m_mechanism.padding_size())
145  {
146  encrypted_data = BigInt::encode(m_blinder.blind(BigInt::decode(encrypted_data)));
147  }
148 
149  secure_vector<uint8_t> decrypted_data;
150  m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
151 
152  // Unblind for RSA/RAW decryption
153  if(!m_mechanism.padding_size())
154  {
155  decrypted_data = BigInt::encode_1363(m_blinder.unblind(BigInt::decode(decrypted_data)), m_key.get_n().bits() / 8 );
156  }
157 
158  valid_mask = 0xFF;
159  return decrypted_data;
160  }
161 
162  private:
163  const PKCS11_RSA_PrivateKey& m_key;
164  MechanismWrapper m_mechanism;
165  size_t m_bits = 0;
166  Fixed_Exponent_Power_Mod m_powermod;
167  Blinder m_blinder;
168  };
169 
170 // note: multiple-part encryption operations (with C_EncryptUpdate/C_EncryptFinal)
171 // are not supported (PK_Ops::Encryption does not provide an `update` method)
172 class PKCS11_RSA_Encryption_Operation final : public PK_Ops::Encryption
173  {
174  public:
175 
176  PKCS11_RSA_Encryption_Operation(const PKCS11_RSA_PublicKey& key, const std::string& padding)
177  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding))
178  {
179  m_bits = 8 * (key.get_n().bytes() - m_mechanism.padding_size()) - 1;
180  }
181 
182  size_t ciphertext_length(size_t) const override { return m_key.get_n().bytes(); }
183 
184  size_t max_input_bits() const override
185  {
186  return m_bits;
187  }
188 
189  secure_vector<uint8_t> encrypt(const uint8_t msg[], size_t msg_len, RandomNumberGenerator&) override
190  {
191  m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
192 
193  secure_vector<uint8_t> encrytped_data;
194  m_key.module()->C_Encrypt(m_key.session().handle(), secure_vector<uint8_t>(msg, msg + msg_len), encrytped_data);
195  return encrytped_data;
196  }
197 
198  private:
199  const PKCS11_RSA_PublicKey& m_key;
200  MechanismWrapper m_mechanism;
201  size_t m_bits = 0;
202  };
203 
204 
205 class PKCS11_RSA_Signature_Operation final : public PK_Ops::Signature
206  {
207  public:
208 
209  PKCS11_RSA_Signature_Operation(const PKCS11_RSA_PrivateKey& key, const std::string& padding)
210  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding))
211  {}
212 
213  size_t signature_length() const override { return m_key.get_n().bytes(); }
214 
215  void update(const uint8_t msg[], size_t msg_len) override
216  {
217  if(!m_initialized)
218  {
219  // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
220  m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
221  m_initialized = true;
222  m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
223  return;
224  }
225 
226  if(!m_first_message.empty())
227  {
228  // second call to update: start multiple-part operation
229  m_key.module()->C_SignUpdate(m_key.session().handle(), m_first_message);
230  m_first_message.clear();
231  }
232 
233  m_key.module()->C_SignUpdate(m_key.session().handle(), const_cast< Byte* >(msg), msg_len);
234  }
235 
236  secure_vector<uint8_t> sign(RandomNumberGenerator&) override
237  {
238  secure_vector<uint8_t> signature;
239  if(!m_first_message.empty())
240  {
241  // single call to update: perform single-part operation
242  m_key.module()->C_Sign(m_key.session().handle(), m_first_message, signature);
243  m_first_message.clear();
244  }
245  else
246  {
247  // multiple calls to update (or none): finish multiple-part operation
248  m_key.module()->C_SignFinal(m_key.session().handle(), signature);
249  }
250  m_initialized = false;
251  return signature;
252  }
253 
254  private:
255  const PKCS11_RSA_PrivateKey& m_key;
256  bool m_initialized = false;
257  secure_vector<uint8_t> m_first_message;
258  MechanismWrapper m_mechanism;
259  };
260 
261 
262 class PKCS11_RSA_Verification_Operation final : public PK_Ops::Verification
263  {
264  public:
265 
266  PKCS11_RSA_Verification_Operation(const PKCS11_RSA_PublicKey& key, const std::string& padding)
267  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding))
268  {}
269 
270  void update(const uint8_t msg[], size_t msg_len) override
271  {
272  if(!m_initialized)
273  {
274  // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
275  m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
276  m_initialized = true;
277  m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
278  return;
279  }
280 
281  if(!m_first_message.empty())
282  {
283  // second call to update: start multiple-part operation
284  m_key.module()->C_VerifyUpdate(m_key.session().handle(), m_first_message);
285  m_first_message.clear();
286  }
287 
288  m_key.module()->C_VerifyUpdate(m_key.session().handle(), const_cast< Byte* >(msg), msg_len);
289  }
290 
291  bool is_valid_signature(const uint8_t sig[], size_t sig_len) override
292  {
294  if(!m_first_message.empty())
295  {
296  // single call to update: perform single-part operation
297  m_key.module()->C_Verify(m_key.session().handle(), m_first_message.data(), m_first_message.size(),
298  const_cast< Byte* >(sig), sig_len, &return_value);
299  m_first_message.clear();
300  }
301  else
302  {
303  // multiple calls to update (or none): finish multiple-part operation
304  m_key.module()->C_VerifyFinal(m_key.session().handle(), const_cast< Byte* >(sig), sig_len, &return_value);
305  }
306  m_initialized = false;
307  if(return_value != ReturnValue::OK && return_value != ReturnValue::SignatureInvalid)
308  {
309  throw PKCS11_ReturnError(return_value);
310  }
311  return return_value == ReturnValue::OK;
312  }
313 
314  private:
315  const PKCS11_RSA_PublicKey& m_key;
316  bool m_initialized = false;
317  secure_vector<uint8_t> m_first_message;
318  MechanismWrapper m_mechanism;
319  };
320 
321 }
322 
323 std::unique_ptr<PK_Ops::Encryption>
324 PKCS11_RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
325  const std::string& params,
326  const std::string& /*provider*/) const
327  {
328  return std::unique_ptr<PK_Ops::Encryption>(new PKCS11_RSA_Encryption_Operation(*this, params));
329  }
330 
331 std::unique_ptr<PK_Ops::Verification>
332 PKCS11_RSA_PublicKey::create_verification_op(const std::string& params,
333  const std::string& /*provider*/) const
334  {
335  return std::unique_ptr<PK_Ops::Verification>(new PKCS11_RSA_Verification_Operation(*this, params));
336  }
337 
338 std::unique_ptr<PK_Ops::Decryption>
339 PKCS11_RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
340  const std::string& params,
341  const std::string& /*provider*/) const
342  {
343  return std::unique_ptr<PK_Ops::Decryption>(new PKCS11_RSA_Decryption_Operation(*this, params, rng));
344  }
345 
346 std::unique_ptr<PK_Ops::Signature>
347 PKCS11_RSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
348  const std::string& params,
349  const std::string& /*provider*/) const
350  {
351  return std::unique_ptr<PK_Ops::Signature>(new PKCS11_RSA_Signature_Operation(*this, params));
352  }
353 
354 PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session, const RSA_PublicKeyGenerationProperties& pub_props,
355  const RSA_PrivateKeyGenerationProperties& priv_props)
356  {
357  ObjectHandle pub_key_handle = 0;
358  ObjectHandle priv_key_handle = 0;
359 
360  Mechanism mechanism = { static_cast< CK_MECHANISM_TYPE >(MechanismType::RsaPkcsKeyPairGen), nullptr, 0 };
361 
362  session.module()->C_GenerateKeyPair(session.handle(), &mechanism,
363  pub_props.data(), pub_props.count(), priv_props.data(), priv_props.count(),
364  &pub_key_handle, &priv_key_handle);
365 
366  return std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle), PKCS11_RSA_PrivateKey(session, priv_key_handle));
367  }
368 
369 }
370 }
371 
372 #endif
#define CK_INVALID_HANDLE
Definition: pkcs11t.h:75
CK_ULONG CK_MECHANISM_TYPE
Definition: pkcs11t.h:583
const BigInt & m_e
Definition: rsa.cpp:395
static std::vector< uint8_t > encode(const BigInt &n)
Definition: bigint.h:678
int(* final)(unsigned char *, CTX *)
CK_ULONG Ulong
Definition: p11.h:836
CK_BYTE Byte
Definition: p11.h:847
std::string decrypt(const uint8_t input[], size_t input_len, const std::string &passphrase)
Definition: cryptobox.cpp:162
BigInt inverse_mod(const BigInt &n, const BigInt &mod)
Definition: numthry.cpp:289
Definition: alg_id.cpp:13
CK_OBJECT_HANDLE ObjectHandle
Definition: p11.h:846
int(* update)(CTX *, const void *, CC_LONG len)
static BigInt decode(const uint8_t buf[], size_t length)
Definition: bigint.h:713
Blinder m_blinder
Definition: rsa.cpp:286
CK_MECHANISM Mechanism
Definition: p11.h:839
static secure_vector< uint8_t > encode_1363(const BigInt &n, size_t bytes)
Definition: big_code.cpp:124
const RSA_PrivateKey & m_key
Definition: rsa.cpp:277
const BigInt & m_n
Definition: rsa.cpp:394
std::string encrypt(const uint8_t input[], size_t input_len, const std::string &passphrase, RandomNumberGenerator &rng)
Definition: cryptobox.cpp:43