Botan 3.4.0
Crypto and TLS for C&
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#include <botan/pk_keys.h>
12
13#if defined(BOTAN_HAS_RSA)
14
15 #include <botan/pubkey.h>
16 #include <botan/rng.h>
17 #include <botan/internal/blinding.h>
18 #include <botan/internal/p11_mechanism.h>
19 #include <botan/internal/pk_ops_impl.h>
20
21namespace Botan::PKCS11 {
22
23RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(const BigInt& modulus, const BigInt& pub_exponent) :
24 PublicKeyProperties(KeyType::Rsa), m_modulus(modulus), m_pub_exponent(pub_exponent) {
25 add_binary(AttributeType::Modulus, BigInt::encode(m_modulus));
26 add_binary(AttributeType::PublicExponent, BigInt::encode(m_pub_exponent));
27}
28
29RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits) : PublicKeyProperties(KeyType::Rsa) {
30 add_numeric(AttributeType::ModulusBits, bits);
31}
32
33PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle) :
34 Object(session, handle),
35 RSA_PublicKey(BigInt::decode(get_attribute_value(AttributeType::Modulus)),
36 BigInt::decode(get_attribute_value(AttributeType::PublicExponent))) {}
37
38PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, const RSA_PublicKeyImportProperties& pubkey_props) :
39 Object(session, pubkey_props), RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()) {}
40
41RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(const BigInt& modulus, const BigInt& priv_exponent) :
42 PrivateKeyProperties(KeyType::Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent) {
43 add_binary(AttributeType::Modulus, BigInt::encode(m_modulus));
44 add_binary(AttributeType::PrivateExponent, BigInt::encode(m_priv_exponent));
45}
46
47PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle) :
48 Object(session, handle),
49 RSA_PublicKey(BigInt::decode(get_attribute_value(AttributeType::Modulus)),
50 BigInt::decode(get_attribute_value(AttributeType::PublicExponent))) {}
51
52PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, const RSA_PrivateKeyImportProperties& priv_key_props) :
53 Object(session, priv_key_props),
54 RSA_PublicKey(priv_key_props.modulus(), BigInt::decode(get_attribute_value(AttributeType::PublicExponent))) {}
55
56PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
57 uint32_t bits,
58 const RSA_PrivateKeyGenerationProperties& priv_key_props) :
59 Object(session), RSA_PublicKey() {
60 RSA_PublicKeyGenerationProperties pub_key_props(bits);
61 pub_key_props.set_encrypt(true);
62 pub_key_props.set_verify(true);
63 pub_key_props.set_token(false); // don't create a persistent public key object
64
65 ObjectHandle pub_key_handle = CK_INVALID_HANDLE;
66 ObjectHandle priv_key_handle = CK_INVALID_HANDLE;
67 Mechanism mechanism = {static_cast<CK_MECHANISM_TYPE>(MechanismType::RsaPkcsKeyPairGen), nullptr, 0};
68 session.module()->C_GenerateKeyPair(session.handle(),
69 &mechanism,
70 pub_key_props.data(),
71 static_cast<Ulong>(pub_key_props.count()),
72 priv_key_props.data(),
73 static_cast<Ulong>(priv_key_props.count()),
74 &pub_key_handle,
75 &priv_key_handle);
76
77 this->reset_handle(priv_key_handle);
78
79 BigInt n = BigInt::decode(get_attribute_value(AttributeType::Modulus));
80 BigInt e = BigInt::decode(get_attribute_value(AttributeType::PublicExponent));
81 RSA_PublicKey::init(std::move(n), std::move(e));
82}
83
84RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key() const {
85 auto p = get_attribute_value(AttributeType::Prime1);
86 auto q = get_attribute_value(AttributeType::Prime2);
87 auto e = get_attribute_value(AttributeType::PublicExponent);
88 auto d = get_attribute_value(AttributeType::PrivateExponent);
89 auto n = get_attribute_value(AttributeType::Modulus);
90
91 return RSA_PrivateKey(BigInt::decode(p), BigInt::decode(q), BigInt::decode(e), BigInt::decode(d), BigInt::decode(n));
92}
93
94std::unique_ptr<Public_Key> PKCS11_RSA_PrivateKey::public_key() const {
95 return std::make_unique<RSA_PublicKey>(BigInt::decode(get_attribute_value(AttributeType::Modulus)),
96 BigInt::decode(get_attribute_value(AttributeType::PublicExponent)));
97}
98
99secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits() const {
100 return export_key().private_key_bits();
101}
102
103namespace {
104// note: multiple-part decryption operations (with C_DecryptUpdate/C_DecryptFinal)
105// are not supported (PK_Ops::Decryption does not provide an `update` method)
106class PKCS11_RSA_Decryption_Operation final : public PK_Ops::Decryption {
107 public:
108 PKCS11_RSA_Decryption_Operation(const PKCS11_RSA_PrivateKey& key,
109 std::string_view padding,
110 RandomNumberGenerator& rng) :
111 m_key(key),
112 m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)),
113 m_blinder(
114 m_key.get_n(),
115 rng,
116 [this](const BigInt& k) { return power_mod(k, m_key.get_e(), m_key.get_n()); },
117 [this](const BigInt& k) { return inverse_mod(k, m_key.get_n()); }) {
118 m_bits = m_key.get_n().bits() - 1;
119 }
120
121 size_t plaintext_length(size_t /*ctext_len*/) const override { return m_key.get_n().bytes(); }
122
123 secure_vector<uint8_t> decrypt(uint8_t& valid_mask, const uint8_t ciphertext[], size_t ciphertext_len) override {
124 valid_mask = 0;
125 m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
126
127 std::vector<uint8_t> encrypted_data(ciphertext, ciphertext + ciphertext_len);
128
129 const size_t modulus_bytes = (m_key.get_n().bits() + 7) / 8;
130
131 // blind for RSA/RAW decryption
132 const bool use_blinding = !m_mechanism.padding_size();
133
134 if(use_blinding) {
135 const BigInt blinded = m_blinder.blind(BigInt::decode(encrypted_data));
136 // SoftHSM at least requires raw RSA inputs be == the modulus size
137 encrypted_data = unlock(BigInt::encode_1363(blinded, modulus_bytes));
138 }
139
140 secure_vector<uint8_t> decrypted_data;
141 m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
142
143 // Unblind for RSA/RAW decryption
144 if(use_blinding) {
145 const BigInt unblinded = m_blinder.unblind(BigInt::decode(decrypted_data));
146 decrypted_data = BigInt::encode_1363(unblinded, modulus_bytes);
147 }
148
149 valid_mask = 0xFF;
150 return decrypted_data;
151 }
152
153 private:
154 const PKCS11_RSA_PrivateKey& m_key;
155 MechanismWrapper m_mechanism;
156 size_t m_bits = 0;
157 Blinder m_blinder;
158};
159
160// note: multiple-part decryption operations (with C_DecryptUpdate/C_DecryptFinal)
161// are not supported (PK_Ops::Decryption does not provide an `update` method)
162class PKCS11_RSA_Decryption_Operation_Software_EME final : public PK_Ops::Decryption_with_EME {
163 public:
164 PKCS11_RSA_Decryption_Operation_Software_EME(const PKCS11_RSA_PrivateKey& key,
165 std::string_view padding,
166 RandomNumberGenerator& rng) :
167 PK_Ops::Decryption_with_EME(padding), m_raw_decryptor(key, rng, "Raw") {}
168
169 size_t plaintext_length(size_t ctext_len) const override { return m_raw_decryptor.plaintext_length(ctext_len); }
170
171 secure_vector<uint8_t> raw_decrypt(const uint8_t input[], size_t input_len) override {
172 return m_raw_decryptor.decrypt(input, input_len);
173 }
174
175 private:
176 PK_Decryptor_EME m_raw_decryptor;
177};
178
179// note: multiple-part encryption operations (with C_EncryptUpdate/C_EncryptFinal)
180// are not supported (PK_Ops::Encryption does not provide an `update` method)
181class PKCS11_RSA_Encryption_Operation final : public PK_Ops::Encryption {
182 public:
183 PKCS11_RSA_Encryption_Operation(const PKCS11_RSA_PublicKey& key, std::string_view padding) :
184 m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)) {
185 m_bits = 8 * (key.get_n().bytes() - m_mechanism.padding_size()) - 1;
186 }
187
188 size_t ciphertext_length(size_t /*ptext_len*/) const override { return m_key.get_n().bytes(); }
189
190 size_t max_input_bits() const override { return m_bits; }
191
192 secure_vector<uint8_t> encrypt(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& /*rng*/) override {
193 m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
194
195 secure_vector<uint8_t> encrytped_data;
196 m_key.module()->C_Encrypt(
197 m_key.session().handle(), secure_vector<uint8_t>(msg, msg + msg_len), encrytped_data);
198 return encrytped_data;
199 }
200
201 private:
202 const PKCS11_RSA_PublicKey& m_key;
203 MechanismWrapper m_mechanism;
204 size_t m_bits = 0;
205};
206
207class PKCS11_RSA_Signature_Operation final : public PK_Ops::Signature {
208 public:
209 PKCS11_RSA_Signature_Operation(const PKCS11_RSA_PrivateKey& key, std::string_view padding) :
210 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
211
212 size_t signature_length() const override { return m_key.get_n().bytes(); }
213
214 void update(const uint8_t msg[], size_t msg_len) override {
215 if(!m_initialized) {
216 // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
217 m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
218 m_initialized = true;
219 m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
220 return;
221 }
222
223 if(!m_first_message.empty()) {
224 // second call to update: start multiple-part operation
225 m_key.module()->C_SignUpdate(m_key.session().handle(), m_first_message);
226 m_first_message.clear();
227 }
228
229 m_key.module()->C_SignUpdate(m_key.session().handle(), msg, static_cast<Ulong>(msg_len));
230 }
231
232 secure_vector<uint8_t> sign(RandomNumberGenerator& /*rng*/) override {
233 secure_vector<uint8_t> signature;
234 if(!m_first_message.empty()) {
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 } else {
239 // multiple calls to update (or none): finish multiple-part operation
240 m_key.module()->C_SignFinal(m_key.session().handle(), signature);
241 }
242 m_initialized = false;
243 return signature;
244 }
245
246 std::string hash_function() const override;
247
248 AlgorithmIdentifier algorithm_identifier() const override;
249
250 private:
251 PKCS11_RSA_PrivateKey m_key;
252 bool m_initialized = false;
253 secure_vector<uint8_t> m_first_message;
254 MechanismWrapper m_mechanism;
255};
256
257namespace {
258
259std::string hash_function_name_from_pkcs11_rsa_mechanism_type(MechanismType type) {
260 switch(type) {
261 case MechanismType::Sha1RsaPkcs:
262 case MechanismType::Sha1RsaPkcsPss:
263 case MechanismType::Sha1RsaX931:
264 return "SHA-1";
265
266 case MechanismType::Sha224RsaPkcs:
267 case MechanismType::Sha224RsaPkcsPss:
268 return "SHA-224";
269
270 case MechanismType::Sha256RsaPkcs:
271 case MechanismType::Sha256RsaPkcsPss:
272 return "SHA-256";
273
274 case MechanismType::Sha384RsaPkcs:
275 case MechanismType::Sha384RsaPkcsPss:
276 return "SHA-384";
277
278 case MechanismType::Sha512RsaPkcs:
279 case MechanismType::Sha512RsaPkcsPss:
280 return "SHA-512";
281
282 case MechanismType::RsaX509:
283 case MechanismType::RsaX931:
284 case MechanismType::RsaPkcs:
285 case MechanismType::RsaPkcsPss:
286 return "Raw";
287
288 default:
289 throw Internal_Error("Unable to determine associated hash function of PKCS11 RSA signature operation");
290 }
291}
292
293} // namespace
294
295std::string PKCS11_RSA_Signature_Operation::hash_function() const {
296 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
297}
298
299AlgorithmIdentifier PKCS11_RSA_Signature_Operation::algorithm_identifier() const {
300 const std::string hash = this->hash_function();
301
302 switch(m_mechanism.mechanism_type()) {
303 case MechanismType::Sha1RsaPkcs:
304 case MechanismType::Sha224RsaPkcs:
305 case MechanismType::Sha256RsaPkcs:
306 case MechanismType::Sha384RsaPkcs:
307 case MechanismType::Sha512RsaPkcs: {
308 const OID oid = OID::from_string("RSA/EMSA3(" + hash + ")");
309 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
310 }
311
312 case MechanismType::Sha1RsaPkcsPss:
313 case MechanismType::Sha224RsaPkcsPss:
314 case MechanismType::Sha256RsaPkcsPss:
315 case MechanismType::Sha384RsaPkcsPss:
316 case MechanismType::Sha512RsaPkcsPss:
317 throw Not_Implemented("RSA-PSS identifier encoding missing for PKCS11");
318
319 default:
320 throw Not_Implemented("No algorithm identifier defined for RSA with this PKCS11 mechanism");
321 }
322}
323
324class PKCS11_RSA_Verification_Operation final : public PK_Ops::Verification {
325 public:
326 PKCS11_RSA_Verification_Operation(const PKCS11_RSA_PublicKey& key, std::string_view padding) :
327 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
328
329 void update(const uint8_t msg[], size_t msg_len) override {
330 if(!m_initialized) {
331 // first call to update: initialize and cache message because we can not determine yet whether a single- or multiple-part operation will be performed
332 m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
333 m_initialized = true;
334 m_first_message = secure_vector<uint8_t>(msg, msg + msg_len);
335 return;
336 }
337
338 if(!m_first_message.empty()) {
339 // second call to update: start multiple-part operation
340 m_key.module()->C_VerifyUpdate(m_key.session().handle(), m_first_message);
341 m_first_message.clear();
342 }
343
344 m_key.module()->C_VerifyUpdate(m_key.session().handle(), msg, static_cast<Ulong>(msg_len));
345 }
346
347 bool is_valid_signature(const uint8_t sig[], size_t sig_len) override {
348 ReturnValue return_value = ReturnValue::SignatureInvalid;
349 if(!m_first_message.empty()) {
350 // single call to update: perform single-part operation
351 m_key.module()->C_Verify(m_key.session().handle(),
352 m_first_message.data(),
353 static_cast<Ulong>(m_first_message.size()),
354 sig,
355 static_cast<Ulong>(sig_len),
356 &return_value);
357 m_first_message.clear();
358 } else {
359 // multiple calls to update (or none): finish multiple-part operation
360 m_key.module()->C_VerifyFinal(m_key.session().handle(), sig, static_cast<Ulong>(sig_len), &return_value);
361 }
362 m_initialized = false;
363 if(return_value != ReturnValue::OK && return_value != ReturnValue::SignatureInvalid) {
364 throw PKCS11_ReturnError(return_value);
365 }
366 return return_value == ReturnValue::OK;
367 }
368
369 std::string hash_function() const override;
370
371 private:
372 const PKCS11_RSA_PublicKey m_key;
373 bool m_initialized = false;
374 secure_vector<uint8_t> m_first_message;
375 MechanismWrapper m_mechanism;
376};
377
378std::string PKCS11_RSA_Verification_Operation::hash_function() const {
379 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
380}
381
382} // namespace
383
384std::unique_ptr<PK_Ops::Encryption> PKCS11_RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
385 std::string_view params,
386 std::string_view /*provider*/) const {
387 return std::make_unique<PKCS11_RSA_Encryption_Operation>(*this, params);
388}
389
390std::unique_ptr<PK_Ops::Verification> PKCS11_RSA_PublicKey::create_verification_op(
391 std::string_view params, std::string_view /*provider*/) const {
392 return std::make_unique<PKCS11_RSA_Verification_Operation>(*this, params);
393}
394
395std::unique_ptr<PK_Ops::Decryption> PKCS11_RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
396 std::string_view params,
397 std::string_view /*provider*/) const {
398 if(params != "Raw" && m_use_software_padding) {
399 return std::make_unique<PKCS11_RSA_Decryption_Operation_Software_EME>(*this, params, rng);
400 } else {
401 return std::make_unique<PKCS11_RSA_Decryption_Operation>(*this, params, rng);
402 }
403}
404
405std::unique_ptr<PK_Ops::Signature> PKCS11_RSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
406 std::string_view params,
407 std::string_view /*provider*/) const {
408 return std::make_unique<PKCS11_RSA_Signature_Operation>(*this, params);
409}
410
411PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session,
412 const RSA_PublicKeyGenerationProperties& pub_props,
413 const RSA_PrivateKeyGenerationProperties& priv_props) {
414 ObjectHandle pub_key_handle = 0;
415 ObjectHandle priv_key_handle = 0;
416
417 Mechanism mechanism = {static_cast<CK_MECHANISM_TYPE>(MechanismType::RsaPkcsKeyPairGen), nullptr, 0};
418
419 session.module()->C_GenerateKeyPair(session.handle(),
420 &mechanism,
421 pub_props.data(),
422 static_cast<Ulong>(pub_props.count()),
423 priv_props.data(),
424 static_cast<Ulong>(priv_props.count()),
425 &pub_key_handle,
426 &priv_key_handle);
427
428 return std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle),
429 PKCS11_RSA_PrivateKey(session, priv_key_handle));
430}
431
432} // namespace Botan::PKCS11
433
434#endif
int(* update)(CTX *, const void *, CC_LONG len)
int(* final)(unsigned char *, CTX *)
std::string encrypt(const uint8_t input[], size_t input_len, std::string_view passphrase, RandomNumberGenerator &rng)
Definition cryptobox.cpp:42
std::string decrypt(const uint8_t input[], size_t input_len, std::string_view passphrase)
secure_vector< uint8_t > decode(DataSource &source, std::string &label)
Definition pem.cpp:62
AttributeType
Definition p11.h:61
CK_MECHANISM Mechanism
Definition p11.h:817
CK_OBJECT_HANDLE ObjectHandle
Definition p11.h:824
CK_ULONG Ulong
Definition p11.h:814
BigInt power_mod(const BigInt &base, const BigInt &exp, const BigInt &mod)
Definition numthry.cpp:286
std::vector< T > unlock(const secure_vector< T > &in)
Definition secmem.h:75
BigInt inverse_mod(const BigInt &n, const BigInt &mod)
Definition mod_inv.cpp:178
#define CK_INVALID_HANDLE
Definition pkcs11t.h:75
CK_ULONG CK_MECHANISM_TYPE
Definition pkcs11t.h:583