9#include <botan/p11_rsa.h>
11#include <botan/pk_keys.h>
13#if defined(BOTAN_HAS_RSA)
15 #include <botan/numthry.h>
16 #include <botan/p11_mechanism.h>
17 #include <botan/pubkey.h>
18 #include <botan/rng.h>
19 #include <botan/internal/blinding.h>
20 #include <botan/internal/mod_inv.h>
21 #include <botan/internal/monty.h>
22 #include <botan/internal/monty_exp.h>
23 #include <botan/internal/pk_ops_impl.h>
24 #include <botan/internal/scoped_cleanup.h>
28RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(
const BigInt& modulus,
const BigInt& pub_exponent) :
30 add_binary(AttributeType::Modulus, m_modulus.serialize());
31 add_binary(AttributeType::PublicExponent, m_pub_exponent.serialize());
34RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits) : PublicKeyProperties(
KeyType::
Rsa) {
35 add_numeric(AttributeType::ModulusBits, bits);
38PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle) :
39 Object(session, handle),
43PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session,
const RSA_PublicKeyImportProperties& pubkey_props) :
44 Object(session, pubkey_props), RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()) {}
46RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(
const BigInt& modulus,
const BigInt& priv_exponent) :
47 PrivateKeyProperties(
KeyType::
Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent) {
48 add_binary(AttributeType::Modulus, m_modulus.serialize());
49 add_binary(AttributeType::PrivateExponent, m_priv_exponent.serialize());
52PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle) :
53 Object(session, handle),
57PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
const RSA_PrivateKeyImportProperties& priv_key_props) :
58 Object(session, priv_key_props),
61PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
63 const RSA_PrivateKeyGenerationProperties& priv_key_props) :
65 RSA_PublicKeyGenerationProperties pub_key_props(bits);
66 pub_key_props.set_encrypt(
true);
67 pub_key_props.set_verify(
true);
68 pub_key_props.set_token(
false);
73 session.module()->C_GenerateKeyPair(session.handle(),
77 priv_key_props.data(),
82 this->reset_handle(priv_key_handle);
83 const Object public_key(session, pub_key_handle);
84 auto destroy_public = scoped_cleanup([&]()
noexcept {
91 BigInt n = BigInt::from_bytes(get_attribute_value(AttributeType::Modulus));
92 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
93 RSA_PublicKey::init(std::move(n), std::move(e));
96RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key()
const {
97 auto p = get_attribute_value(AttributeType::Prime1);
98 auto q = get_attribute_value(AttributeType::Prime2);
99 auto e = get_attribute_value(AttributeType::PublicExponent);
100 auto d = get_attribute_value(AttributeType::PrivateExponent);
101 auto n = get_attribute_value(AttributeType::Modulus);
103 return RSA_PrivateKey(BigInt::from_bytes(p),
104 BigInt::from_bytes(q),
105 BigInt::from_bytes(e),
106 BigInt::from_bytes(d),
107 BigInt::from_bytes(n));
110std::unique_ptr<Public_Key> PKCS11_RSA_PrivateKey::public_key()
const {
111 return std::make_unique<RSA_PublicKey>(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
112 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent)));
115secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits()
const {
116 return export_key().private_key_bits();
122class PKCS11_RSA_Decryption_Operation final :
public PK_Ops::Decryption {
124 PKCS11_RSA_Decryption_Operation(
const PKCS11_RSA_PrivateKey& key,
125 std::string_view padding,
126 RandomNumberGenerator& rng) :
128 m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)),
129 m_mod_n(Barrett_Reduction::for_public_modulus(m_key.get_n())),
130 m_monty_n(m_key.get_n(), m_mod_n),
131 m_bits(m_key.get_n().bits() - 1),
135 [this](const BigInt& k) {
136 const size_t powm_window = 1;
142 size_t plaintext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
144 size_t ciphertext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
146 secure_vector<uint8_t>
decrypt(uint8_t& valid_mask, std::span<const uint8_t> ctext)
override {
149 const size_t modulus_bytes = (m_key.get_n().bits() + 7) / 8;
152 const bool use_blinding = m_mechanism.padding_size() == 0;
154 std::vector<uint8_t> encrypted_data(ctext.begin(), ctext.end());
159 if(encrypted_data.size() > modulus_bytes) {
160 return secure_vector<uint8_t>{};
162 const BigInt input_bn = BigInt::from_bytes(encrypted_data);
163 if(input_bn.is_zero() || input_bn >= m_key.get_n()) {
164 return secure_vector<uint8_t>{};
166 const BigInt blinded = m_blinder.blind(input_bn);
168 encrypted_data = blinded.serialize(modulus_bytes);
171 m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
173 secure_vector<uint8_t> decrypted_data;
175 m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
177 }
catch(PKCS11_Error&) {
178 decrypted_data.clear();
183 const BigInt unblinded = m_blinder.unblind(BigInt::from_bytes(decrypted_data));
184 decrypted_data.resize(modulus_bytes);
185 unblinded.serialize_to(decrypted_data);
188 return decrypted_data;
192 PKCS11_RSA_PrivateKey m_key;
193 MechanismWrapper m_mechanism;
194 Barrett_Reduction m_mod_n;
195 const Montgomery_Params m_monty_n;
202class PKCS11_RSA_Decryption_Operation_Software_EME final :
public PK_Ops::Decryption_with_Padding {
204 PKCS11_RSA_Decryption_Operation_Software_EME(
const PKCS11_RSA_PrivateKey& key,
205 std::string_view padding,
206 RandomNumberGenerator& rng) :
207 PK_Ops::Decryption_with_Padding(padding), m_raw_op(key,
"Raw", rng) {}
209 size_t plaintext_length(
size_t ctext_len)
const override {
return m_raw_op.plaintext_length(ctext_len); }
211 size_t ciphertext_length(
size_t ptext_len)
const override {
return m_raw_op.ciphertext_length(ptext_len); }
213 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input)
override {
216 uint8_t valid_mask = 0;
217 return m_raw_op.decrypt(valid_mask, input);
221 PKCS11_RSA_Decryption_Operation m_raw_op;
226class PKCS11_RSA_Encryption_Operation final :
public PK_Ops::Encryption {
228 PKCS11_RSA_Encryption_Operation(
const PKCS11_RSA_PublicKey& key, std::string_view padding) :
229 m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)) {
230 const size_t k = key.get_n().bytes();
231 const size_t pad = m_mechanism.padding_size();
235 m_bits = 8 * (k - pad);
241 size_t ciphertext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
243 size_t max_input_bits()
const override {
return m_bits; }
245 std::vector<uint8_t>
encrypt(std::span<const uint8_t> input, RandomNumberGenerator& )
override {
246 m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
248 std::vector<uint8_t> encrypted_data;
249 m_key.module()->C_Encrypt(
250 m_key.session().handle(), secure_vector<uint8_t>(input.begin(), input.end()), encrypted_data);
251 return encrypted_data;
255 PKCS11_RSA_PublicKey m_key;
256 MechanismWrapper m_mechanism;
260class PKCS11_RSA_Signature_Operation final :
public PK_Ops::Signature {
262 PKCS11_RSA_Signature_Operation(
const PKCS11_RSA_PrivateKey& key, std::string_view padding) :
263 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
265 size_t signature_length()
const override {
return m_key.get_n().bytes(); }
267 void update(std::span<const uint8_t> input)
override {
270 m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
271 m_initialized =
true;
272 m_first_message.assign(input.begin(), input.end());
273 m_has_first_message =
true;
277 if(m_has_first_message) {
279 m_key.module()->C_SignUpdate(m_key.session().handle(), m_first_message);
280 m_first_message.clear();
281 m_has_first_message =
false;
284 m_key.module()->C_SignUpdate(m_key.session().handle(), input.data(),
checked_ulong_cast(input.size()));
287 std::vector<uint8_t> sign(RandomNumberGenerator& )
override {
290 m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
291 m_initialized =
true;
292 m_has_first_message =
true;
294 std::vector<uint8_t> signature;
295 if(m_has_first_message) {
297 m_key.module()->C_Sign(m_key.session().handle(), m_first_message, signature);
298 m_first_message.clear();
299 m_has_first_message =
false;
302 m_key.module()->C_SignFinal(m_key.session().handle(), signature);
304 m_initialized =
false;
308 std::string hash_function()
const override;
310 AlgorithmIdentifier algorithm_identifier()
const override;
313 PKCS11_RSA_PrivateKey m_key;
314 bool m_initialized =
false;
315 bool m_has_first_message =
false;
316 secure_vector<uint8_t> m_first_message;
317 MechanismWrapper m_mechanism;
322std::string hash_function_name_from_pkcs11_rsa_mechanism_type(MechanismType type) {
324 case MechanismType::Sha1RsaPkcs:
325 case MechanismType::Sha1RsaPkcsPss:
326 case MechanismType::Sha1RsaX931:
329 case MechanismType::Sha224RsaPkcs:
330 case MechanismType::Sha224RsaPkcsPss:
333 case MechanismType::Sha256RsaPkcs:
334 case MechanismType::Sha256RsaPkcsPss:
337 case MechanismType::Sha384RsaPkcs:
338 case MechanismType::Sha384RsaPkcsPss:
341 case MechanismType::Sha512RsaPkcs:
342 case MechanismType::Sha512RsaPkcsPss:
345 case MechanismType::RsaX509:
346 case MechanismType::RsaX931:
347 case MechanismType::RsaPkcs:
348 case MechanismType::RsaPkcsPss:
352 throw Internal_Error(
"Unable to determine associated hash function of PKCS11 RSA signature operation");
358std::string PKCS11_RSA_Signature_Operation::hash_function()
const {
359 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
362AlgorithmIdentifier PKCS11_RSA_Signature_Operation::algorithm_identifier()
const {
363 const std::string hash = this->hash_function();
365 switch(m_mechanism.mechanism_type()) {
366 case MechanismType::Sha1RsaPkcs:
367 case MechanismType::Sha224RsaPkcs:
368 case MechanismType::Sha256RsaPkcs:
369 case MechanismType::Sha384RsaPkcs:
370 case MechanismType::Sha512RsaPkcs: {
371 const OID oid = OID::from_string(
"RSA/EMSA3(" + hash +
")");
372 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
375 case MechanismType::Sha1RsaPkcsPss:
376 case MechanismType::Sha224RsaPkcsPss:
377 case MechanismType::Sha256RsaPkcsPss:
378 case MechanismType::Sha384RsaPkcsPss:
379 case MechanismType::Sha512RsaPkcsPss:
380 throw Not_Implemented(
"RSA-PSS identifier encoding missing for PKCS11");
383 throw Not_Implemented(
"No algorithm identifier defined for RSA with this PKCS11 mechanism");
387class PKCS11_RSA_Verification_Operation final :
public PK_Ops::Verification {
389 PKCS11_RSA_Verification_Operation(
const PKCS11_RSA_PublicKey& key, std::string_view padding) :
390 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
392 void update(std::span<const uint8_t> input)
override {
395 m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
396 m_initialized =
true;
397 m_first_message.assign(input.begin(), input.end());
398 m_has_first_message =
true;
402 if(m_has_first_message) {
404 m_key.module()->C_VerifyUpdate(m_key.session().handle(), m_first_message);
405 m_first_message.clear();
406 m_has_first_message =
false;
409 m_key.module()->C_VerifyUpdate(m_key.session().handle(), input.data(),
checked_ulong_cast(input.size()));
412 bool is_valid_signature(std::span<const uint8_t> sig)
override {
415 m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
416 m_initialized =
true;
417 m_has_first_message =
true;
419 ReturnValue return_value = ReturnValue::SignatureInvalid;
420 if(m_has_first_message) {
422 m_key.module()->C_Verify(m_key.session().handle(),
423 m_first_message.data(),
428 m_first_message.clear();
429 m_has_first_message =
false;
432 m_key.module()->C_VerifyFinal(
435 m_initialized =
false;
436 if(return_value == ReturnValue::SignatureInvalid || return_value == ReturnValue::SignatureLenRange) {
438 }
else if(return_value == ReturnValue::OK) {
441 throw PKCS11_ReturnError(return_value);
445 std::string hash_function()
const override;
448 const PKCS11_RSA_PublicKey m_key;
449 bool m_initialized =
false;
450 bool m_has_first_message =
false;
451 secure_vector<uint8_t> m_first_message;
452 MechanismWrapper m_mechanism;
455std::string PKCS11_RSA_Verification_Operation::hash_function()
const {
456 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
461std::unique_ptr<PK_Ops::Encryption> PKCS11_RSA_PublicKey::create_encryption_op(RandomNumberGenerator& ,
462 std::string_view params,
463 std::string_view )
const {
464 return std::make_unique<PKCS11_RSA_Encryption_Operation>(*
this, params);
467std::unique_ptr<PK_Ops::Verification> PKCS11_RSA_PublicKey::create_verification_op(
468 std::string_view params, std::string_view )
const {
469 return std::make_unique<PKCS11_RSA_Verification_Operation>(*
this, params);
472std::unique_ptr<PK_Ops::Decryption> PKCS11_RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
473 std::string_view params,
474 std::string_view )
const {
475 if(params !=
"Raw" && m_use_software_padding) {
476 return std::make_unique<PKCS11_RSA_Decryption_Operation_Software_EME>(*
this, params, rng);
478 return std::make_unique<PKCS11_RSA_Decryption_Operation>(*
this, params, rng);
482std::unique_ptr<PK_Ops::Signature> PKCS11_RSA_PrivateKey::create_signature_op(RandomNumberGenerator& ,
483 std::string_view params,
484 std::string_view )
const {
485 return std::make_unique<PKCS11_RSA_Signature_Operation>(*
this, params);
488PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session,
489 const RSA_PublicKeyGenerationProperties& pub_props,
490 const RSA_PrivateKeyGenerationProperties& priv_props) {
496 session.module()->C_GenerateKeyPair(session.handle(),
505 return std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle),
506 PKCS11_RSA_PrivateKey(session, priv_key_handle));
Common attributes of all public key objects.
std::string decrypt(std::span< const uint8_t > input, std::string_view passphrase)
std::string encrypt(const uint8_t input[], size_t input_len, std::string_view passphrase, RandomNumberGenerator &rng)
Ulong checked_ulong_cast(size_t v)
CK_OBJECT_HANDLE ObjectHandle
std::shared_ptr< const Montgomery_Exponentiation_State > monty_precompute(const Montgomery_Int &g, size_t window_bits, bool const_time)
Montgomery_Int monty_execute_vartime(const Montgomery_Exponentiation_State &precomputed_state, const BigInt &k)
BigInt inverse_mod_rsa_public_modulus(const BigInt &x, const BigInt &n)
#define CK_INVALID_HANDLE
CK_ULONG CK_MECHANISM_TYPE