Botan  2.6.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  secure_vector<uint8_t> decrypt(uint8_t& valid_mask, const uint8_t ciphertext[], size_t ciphertext_len) override
135  {
136  valid_mask = 0;
137  m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
138 
139  std::vector<uint8_t> encrypted_data(ciphertext, ciphertext + ciphertext_len);
140 
141  // blind for RSA/RAW decryption
142  if(! m_mechanism.padding_size())
143  {
144  encrypted_data = BigInt::encode(m_blinder.blind(BigInt::decode(encrypted_data)));
145  }
146 
147  secure_vector<uint8_t> decrypted_data;
148  m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
149 
150  // Unblind for RSA/RAW decryption
151  if(!m_mechanism.padding_size())
152  {
153  decrypted_data = BigInt::encode_1363(m_blinder.unblind(BigInt::decode(decrypted_data)), m_key.get_n().bits() / 8 );
154  }
155 
156  valid_mask = 0xFF;
157  return decrypted_data;
158  }
159 
160  private:
161  const PKCS11_RSA_PrivateKey& m_key;
162  MechanismWrapper m_mechanism;
163  size_t m_bits = 0;
164  Fixed_Exponent_Power_Mod m_powermod;
165  Blinder m_blinder;
166  };
167 
168 // note: multiple-part encryption operations (with C_EncryptUpdate/C_EncryptFinal)
169 // are not supported (PK_Ops::Encryption does not provide an `update` method)
170 class PKCS11_RSA_Encryption_Operation final : public PK_Ops::Encryption
171  {
172  public:
173 
174  PKCS11_RSA_Encryption_Operation(const PKCS11_RSA_PublicKey& key, const std::string& padding)
175  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding))
176  {
177  m_bits = 8 * (key.get_n().bytes() - m_mechanism.padding_size()) - 1;
178  }
179 
180  size_t max_input_bits() const override
181  {
182  return m_bits;
183  }
184 
185  secure_vector<uint8_t> encrypt(const uint8_t msg[], size_t msg_len, RandomNumberGenerator&) override
186  {
187  m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
188 
189  secure_vector<uint8_t> encrytped_data;
190  m_key.module()->C_Encrypt(m_key.session().handle(), secure_vector<uint8_t>(msg, msg + msg_len), encrytped_data);
191  return encrytped_data;
192  }
193 
194  private:
195  const PKCS11_RSA_PublicKey& m_key;
196  MechanismWrapper m_mechanism;
197  size_t m_bits = 0;
198  };
199 
200 
201 class PKCS11_RSA_Signature_Operation final : public PK_Ops::Signature
202  {
203  public:
204 
205  PKCS11_RSA_Signature_Operation(const PKCS11_RSA_PrivateKey& key, const std::string& padding)
206  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding))
207  {}
208 
209  void update(const uint8_t msg[], size_t msg_len) override
210  {
211  if(!m_initialized)
212  {
213  // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
214  m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
215  m_initialized = true;
216  m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
217  return;
218  }
219 
220  if(!m_first_message.empty())
221  {
222  // second call to update: start multiple-part operation
223  m_key.module()->C_SignUpdate(m_key.session().handle(), m_first_message);
224  m_first_message.clear();
225  }
226 
227  m_key.module()->C_SignUpdate(m_key.session().handle(), const_cast< Byte* >(msg), msg_len);
228  }
229 
230  secure_vector<uint8_t> sign(RandomNumberGenerator&) override
231  {
232  secure_vector<uint8_t> signature;
233  if(!m_first_message.empty())
234  {
235  // single call to update: perform single-part operation
236  m_key.module()->C_Sign(m_key.session().handle(), m_first_message, signature);
237  m_first_message.clear();
238  }
239  else
240  {
241  // multiple calls to update (or none): finish multiple-part operation
242  m_key.module()->C_SignFinal(m_key.session().handle(), signature);
243  }
244  m_initialized = false;
245  return signature;
246  }
247 
248  private:
249  const PKCS11_RSA_PrivateKey& m_key;
250  bool m_initialized = false;
251  secure_vector<uint8_t> m_first_message;
252  MechanismWrapper m_mechanism;
253  };
254 
255 
256 class PKCS11_RSA_Verification_Operation final : public PK_Ops::Verification
257  {
258  public:
259 
260  PKCS11_RSA_Verification_Operation(const PKCS11_RSA_PublicKey& key, const std::string& padding)
261  : m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding))
262  {}
263 
264  void update(const uint8_t msg[], size_t msg_len) override
265  {
266  if(!m_initialized)
267  {
268  // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
269  m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
270  m_initialized = true;
271  m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
272  return;
273  }
274 
275  if(!m_first_message.empty())
276  {
277  // second call to update: start multiple-part operation
278  m_key.module()->C_VerifyUpdate(m_key.session().handle(), m_first_message);
279  m_first_message.clear();
280  }
281 
282  m_key.module()->C_VerifyUpdate(m_key.session().handle(), const_cast< Byte* >(msg), msg_len);
283  }
284 
285  bool is_valid_signature(const uint8_t sig[], size_t sig_len) override
286  {
288  if(!m_first_message.empty())
289  {
290  // single call to update: perform single-part operation
291  m_key.module()->C_Verify(m_key.session().handle(), m_first_message.data(), m_first_message.size(),
292  const_cast< Byte* >(sig), sig_len, &return_value);
293  m_first_message.clear();
294  }
295  else
296  {
297  // multiple calls to update (or none): finish multiple-part operation
298  m_key.module()->C_VerifyFinal(m_key.session().handle(), const_cast< Byte* >(sig), sig_len, &return_value);
299  }
300  m_initialized = false;
301  if(return_value != ReturnValue::OK && return_value != ReturnValue::SignatureInvalid)
302  {
303  throw PKCS11_ReturnError(return_value);
304  }
305  return return_value == ReturnValue::OK;
306  }
307 
308  private:
309  const PKCS11_RSA_PublicKey& m_key;
310  bool m_initialized = false;
311  secure_vector<uint8_t> m_first_message;
312  MechanismWrapper m_mechanism;
313  };
314 
315 }
316 
317 std::unique_ptr<PK_Ops::Encryption>
318 PKCS11_RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
319  const std::string& params,
320  const std::string& /*provider*/) const
321  {
322  return std::unique_ptr<PK_Ops::Encryption>(new PKCS11_RSA_Encryption_Operation(*this, params));
323  }
324 
325 std::unique_ptr<PK_Ops::Verification>
326 PKCS11_RSA_PublicKey::create_verification_op(const std::string& params,
327  const std::string& /*provider*/) const
328  {
329  return std::unique_ptr<PK_Ops::Verification>(new PKCS11_RSA_Verification_Operation(*this, params));
330  }
331 
332 std::unique_ptr<PK_Ops::Decryption>
333 PKCS11_RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
334  const std::string& params,
335  const std::string& /*provider*/) const
336  {
337  return std::unique_ptr<PK_Ops::Decryption>(new PKCS11_RSA_Decryption_Operation(*this, params, rng));
338  }
339 
340 std::unique_ptr<PK_Ops::Signature>
341 PKCS11_RSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
342  const std::string& params,
343  const std::string& /*provider*/) const
344  {
345  return std::unique_ptr<PK_Ops::Signature>(new PKCS11_RSA_Signature_Operation(*this, params));
346  }
347 
348 PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session, const RSA_PublicKeyGenerationProperties& pub_props,
349  const RSA_PrivateKeyGenerationProperties& priv_props)
350  {
351  ObjectHandle pub_key_handle = 0;
352  ObjectHandle priv_key_handle = 0;
353 
354  Mechanism mechanism = { static_cast< CK_MECHANISM_TYPE >(MechanismType::RsaPkcsKeyPairGen), nullptr, 0 };
355 
356  session.module()->C_GenerateKeyPair(session.handle(), &mechanism,
357  pub_props.data(), pub_props.count(), priv_props.data(), priv_props.count(),
358  &pub_key_handle, &priv_key_handle);
359 
360  return std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle), PKCS11_RSA_PrivateKey(session, priv_key_handle));
361  }
362 
363 }
364 }
365 
366 #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:366
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:279
Definition: alg_id.cpp:13
CK_OBJECT_HANDLE ObjectHandle
Definition: p11.h:846
Blinder m_blinder
Definition: rsa.cpp:264
CK_MECHANISM Mechanism
Definition: p11.h:839
static secure_vector< uint8_t > encode_1363(const BigInt &n, size_t bytes)
Definition: big_code.cpp:82
static std::vector< uint8_t > encode(const BigInt &n, Base base=Binary)
Definition: big_code.cpp:54
const RSA_PrivateKey & m_key
Definition: rsa.cpp:255
const BigInt & m_n
Definition: rsa.cpp:365
std::string encrypt(const uint8_t input[], size_t input_len, const std::string &passphrase, RandomNumberGenerator &rng)
Definition: cryptobox.cpp:43
static BigInt decode(const uint8_t buf[], size_t length, Base base=Binary)
Definition: big_code.cpp:114