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