9#include <botan/p11_rsa.h>
11#include <botan/pk_keys.h>
13#if defined(BOTAN_HAS_RSA)
15 #include <botan/assert.h>
16 #include <botan/mem_ops.h>
17 #include <botan/numthry.h>
18 #include <botan/p11_mechanism.h>
19 #include <botan/pk_options_readers.h>
20 #include <botan/pss_params.h>
21 #include <botan/pubkey.h>
22 #include <botan/rng.h>
23 #include <botan/internal/blinding.h>
24 #include <botan/internal/mod_inv.h>
25 #include <botan/internal/monty.h>
26 #include <botan/internal/monty_exp.h>
27 #include <botan/internal/p11_object_guard.h>
28 #include <botan/internal/p11_sig_stream.h>
29 #include <botan/internal/pk_ops_impl.h>
30 #include <botan/internal/pk_options_impl.h>
34RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(
const BigInt& modulus,
const BigInt& pub_exponent) :
36 add_binary(AttributeType::Modulus, m_modulus.serialize());
37 add_binary(AttributeType::PublicExponent, m_pub_exponent.serialize());
40RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits) : PublicKeyProperties(
KeyType::
Rsa) {
41 add_numeric(AttributeType::ModulusBits, bits);
44PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle) :
45 Object(session, handle),
52const RSA_PublicKeyImportProperties& check_rsa_public_key(
const RSA_PublicKeyImportProperties& props) {
53 const RSA_PublicKey key(props.modulus(), props.pub_exponent());
60PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session,
const RSA_PublicKeyImportProperties& pubkey_props) :
61 Object(session, check_rsa_public_key(pubkey_props)),
62 RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()) {}
64RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(
const BigInt& modulus,
const BigInt& priv_exponent) :
65 PrivateKeyProperties(
KeyType::
Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent) {
66 add_binary(AttributeType::Modulus, m_modulus.serialize());
67 add_binary(AttributeType::PrivateExponent, m_priv_exponent.serialize());
70PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle) :
71 Object(session, handle),
75PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
const RSA_PrivateKeyImportProperties& priv_key_props) :
76 Object(session, priv_key_props) {
77 Object_Creation_Guard guard(session, {handle()});
78 BigInt n = priv_key_props.modulus();
79 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
80 RSA_PublicKey::init(std::move(n), std::move(e));
84PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
86 const RSA_PrivateKeyGenerationProperties& priv_key_props) :
88 RSA_PublicKeyGenerationProperties pub_key_props(bits);
89 pub_key_props.set_encrypt(
true);
90 pub_key_props.set_verify(
true);
91 pub_key_props.set_token(
false);
96 session.module()->C_GenerateKeyPair(session.handle(),
100 priv_key_props.data(),
106 const Object_Creation_Guard destroy_public(session, {pub_key_handle});
107 Object_Creation_Guard guard(session, {priv_key_handle});
109 this->reset_handle(priv_key_handle);
111 BigInt n = BigInt::from_bytes(get_attribute_value(AttributeType::Modulus));
112 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
113 RSA_PublicKey::init(std::move(n), std::move(e));
117RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key()
const {
118 auto p = get_attribute_value(AttributeType::Prime1);
119 auto q = get_attribute_value(AttributeType::Prime2);
120 auto e = get_attribute_value(AttributeType::PublicExponent);
121 auto d = get_attribute_value(AttributeType::PrivateExponent);
122 auto n = get_attribute_value(AttributeType::Modulus);
124 return RSA_PrivateKey(BigInt::from_bytes(p),
125 BigInt::from_bytes(q),
126 BigInt::from_bytes(e),
127 BigInt::from_bytes(d),
128 BigInt::from_bytes(n));
131std::unique_ptr<Public_Key> PKCS11_RSA_PrivateKey::public_key()
const {
132 return std::make_unique<RSA_PublicKey>(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
133 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent)));
136secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits()
const {
137 return export_key().private_key_bits();
143class PKCS11_RSA_Decryption_Operation final :
public PK_Ops::Decryption {
145 PKCS11_RSA_Decryption_Operation(
const PKCS11_RSA_PrivateKey& key,
146 const PK_Encryption_Options_Reader& options,
147 RandomNumberGenerator& rng) :
149 m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(options)),
150 m_mod_n(Barrett_Reduction::for_public_modulus(m_key.get_n())),
151 m_monty_n(m_key.get_n(), m_mod_n),
152 m_bits(m_key.get_n().bits() - 1),
156 [this](const BigInt& k) {
157 const size_t powm_window = 1;
163 size_t plaintext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
165 size_t ciphertext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
167 size_t decrypt(uint8_t& valid_mask, std::span<uint8_t> ptext, std::span<const uint8_t> ctext)
override {
170 const size_t modulus_bytes = (m_key.get_n().bits() + 7) / 8;
173 const bool use_blinding = m_mechanism.padding_size() == 0;
175 std::vector<uint8_t> encrypted_data(ctext.begin(), ctext.end());
180 if(encrypted_data.size() != modulus_bytes) {
183 const BigInt input_bn = BigInt::from_bytes(encrypted_data);
184 if(input_bn.is_zero() || input_bn >= m_key.get_n()) {
187 const BigInt blinded = m_blinder.blind(input_bn);
189 encrypted_data = blinded.serialize(modulus_bytes);
192 m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
194 secure_vector<uint8_t> decrypted_data;
196 m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
198 }
catch(PKCS11_Error&) {
199 decrypted_data.clear();
204 const BigInt unblinded = m_blinder.unblind(BigInt::from_bytes(decrypted_data));
205 decrypted_data.resize(modulus_bytes);
206 unblinded.serialize_to(decrypted_data);
209 BOTAN_ARG_CHECK(ptext.size() >= decrypted_data.size(),
"Output buffer too small for decryption");
210 copy_mem(ptext.first(decrypted_data.size()), decrypted_data);
211 return decrypted_data.size();
215 PKCS11_RSA_PrivateKey m_key;
216 MechanismWrapper m_mechanism;
217 Barrett_Reduction m_mod_n;
218 const Montgomery_Params m_monty_n;
225class PKCS11_RSA_Decryption_Operation_Software_EME final :
public PK_Ops::Decryption_with_Padding {
227 PKCS11_RSA_Decryption_Operation_Software_EME(
const PKCS11_RSA_PrivateKey& key,
228 const PK_Encryption_Options_Reader& options,
229 RandomNumberGenerator& rng) :
230 PK_Ops::Decryption_with_Padding(options),
231 m_raw_op(key, PK_Options_Reader_Access::
read(PK_Encryption_Options().with_padding(
"Raw")), rng) {}
233 size_t plaintext_length(
size_t ctext_len)
const override {
return m_raw_op.plaintext_length(ctext_len); }
235 size_t ciphertext_length(
size_t ptext_len)
const override {
return m_raw_op.ciphertext_length(ptext_len); }
237 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input)
override {
244 if(input.size() != m_raw_op.ciphertext_length(0)) {
245 throw Decoding_Error(
"RSA ciphertext is an incorrect size for this public key");
250 uint8_t valid_mask = 0;
251 secure_vector<uint8_t> raw(m_raw_op.plaintext_length(input.size()));
252 raw.resize(m_raw_op.decrypt(valid_mask, raw, input));
257 PKCS11_RSA_Decryption_Operation m_raw_op;
262class PKCS11_RSA_Encryption_Operation final :
public PK_Ops::Encryption {
264 PKCS11_RSA_Encryption_Operation(
const PKCS11_RSA_PublicKey& key,
const PK_Encryption_Options_Reader& options) :
265 m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(options)) {
266 const size_t k = key.get_n().bytes();
267 const size_t pad = m_mechanism.padding_size();
271 m_bits = 8 * (k - pad);
277 size_t ciphertext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
279 size_t max_input_bits()
const override {
return m_bits; }
281 std::vector<uint8_t>
encrypt(std::span<const uint8_t> input, RandomNumberGenerator& )
override {
282 m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
284 std::vector<uint8_t> encrypted_data;
285 m_key.module()->C_Encrypt(
286 m_key.session().handle(), secure_vector<uint8_t>(input.begin(), input.end()), encrypted_data);
287 return encrypted_data;
291 PKCS11_RSA_PublicKey m_key;
292 MechanismWrapper m_mechanism;
296class PKCS11_RSA_Signature_Operation final :
public PK_Ops::Signature {
298 PKCS11_RSA_Signature_Operation(
const PKCS11_RSA_PrivateKey& key,
const PK_Signature_Options_Reader& options) :
300 m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(options)),
301 m_stream(Signature_Stream::Direction::
Sign, m_key, m_mechanism) {}
303 size_t signature_length()
const override {
return m_key.get_n().bytes(); }
305 void update(std::span<const uint8_t> input)
override { m_stream.update(input); }
307 std::vector<uint8_t> sign(RandomNumberGenerator& )
override {
308 auto signature = m_stream.sign();
309 if(signature.size() != signature_length()) {
310 throw PKCS11_Error(
"PKCS #11 module returned an RSA signature of unexpected length");
315 std::string hash_function()
const override;
317 AlgorithmIdentifier algorithm_identifier()
const override;
320 PKCS11_RSA_PrivateKey m_key;
321 MechanismWrapper m_mechanism;
322 Signature_Stream m_stream;
327std::string hash_function_name_from_pkcs11_rsa_mechanism_type(MechanismType type) {
329 case MechanismType::Sha1RsaPkcs:
330 case MechanismType::Sha1RsaPkcsPss:
331 case MechanismType::Sha1RsaX931:
334 case MechanismType::Sha224RsaPkcs:
335 case MechanismType::Sha224RsaPkcsPss:
338 case MechanismType::Sha256RsaPkcs:
339 case MechanismType::Sha256RsaPkcsPss:
342 case MechanismType::Sha384RsaPkcs:
343 case MechanismType::Sha384RsaPkcsPss:
346 case MechanismType::Sha512RsaPkcs:
347 case MechanismType::Sha512RsaPkcsPss:
350 case MechanismType::RsaX509:
351 case MechanismType::RsaX931:
352 case MechanismType::RsaPkcs:
353 case MechanismType::RsaPkcsPss:
357 throw Internal_Error(
"Unable to determine associated hash function of PKCS11 RSA signature operation");
363std::string PKCS11_RSA_Signature_Operation::hash_function()
const {
364 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
367AlgorithmIdentifier PKCS11_RSA_Signature_Operation::algorithm_identifier()
const {
368 const std::string hash = this->hash_function();
370 switch(m_mechanism.mechanism_type()) {
371 case MechanismType::Sha1RsaPkcs:
372 case MechanismType::Sha224RsaPkcs:
373 case MechanismType::Sha256RsaPkcs:
374 case MechanismType::Sha384RsaPkcs:
375 case MechanismType::Sha512RsaPkcs: {
376 const OID oid = OID::from_string(
"RSA/EMSA3(" + hash +
")");
377 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
380 case MechanismType::Sha1RsaPkcsPss:
381 case MechanismType::Sha224RsaPkcsPss:
382 case MechanismType::Sha256RsaPkcsPss:
383 case MechanismType::Sha384RsaPkcsPss:
384 case MechanismType::Sha512RsaPkcsPss: {
386 const auto* pss =
static_cast<const RsaPkcsPssParams*
>(m_mechanism.data()->pParameter);
388 return AlgorithmIdentifier(
"RSA/PSS", PSS_Params(hash, pss->sLen).serialize());
392 throw Not_Implemented(
"No algorithm identifier defined for RSA with this PKCS11 mechanism");
396class PKCS11_RSA_Verification_Operation final :
public PK_Ops::Verification {
398 PKCS11_RSA_Verification_Operation(
const PKCS11_RSA_PublicKey& key,
const PK_Signature_Options_Reader& options) :
400 m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(options)),
401 m_stream(Signature_Stream::Direction::
Verify, m_key, m_mechanism) {}
403 void update(std::span<const uint8_t> input)
override { m_stream.update(input); }
405 bool is_valid_signature(std::span<const uint8_t> sig)
override {
return m_stream.verify(sig); }
407 std::string hash_function()
const override;
410 const PKCS11_RSA_PublicKey m_key;
411 MechanismWrapper m_mechanism;
412 Signature_Stream m_stream;
415std::string PKCS11_RSA_Verification_Operation::hash_function()
const {
416 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
421std::unique_ptr<PK_Ops::Encryption> PKCS11_RSA_PublicKey::_create_encryption_op(
422 RandomNumberGenerator& rng,
const PK_Encryption_Options_Reader& options)
const {
425 return std::make_unique<PKCS11_RSA_Encryption_Operation>(*
this, options);
428std::unique_ptr<PK_Ops::Verification> PKCS11_RSA_PublicKey::_create_verification_op(
429 const PK_Signature_Options_Reader& options)
const {
431 return std::make_unique<PKCS11_RSA_Verification_Operation>(*
this, options);
434std::unique_ptr<PK_Ops::Decryption> PKCS11_RSA_PrivateKey::_create_decryption_op(
435 RandomNumberGenerator& rng,
const PK_Encryption_Options_Reader& options)
const {
437 if(m_use_software_padding && options.padding().value_or(
"Raw") !=
"Raw") {
438 return std::make_unique<PKCS11_RSA_Decryption_Operation_Software_EME>(*
this, options, rng);
440 return std::make_unique<PKCS11_RSA_Decryption_Operation>(*
this, options, rng);
444std::unique_ptr<PK_Ops::Signature> PKCS11_RSA_PrivateKey::_create_signature_op(
445 RandomNumberGenerator& rng,
const PK_Signature_Options_Reader& options)
const {
448 return std::make_unique<PKCS11_RSA_Signature_Operation>(*
this, options);
451PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session,
452 const RSA_PublicKeyGenerationProperties& pub_props,
453 const RSA_PrivateKeyGenerationProperties& priv_props) {
459 session.module()->C_GenerateKeyPair(session.handle(),
468 Object_Creation_Guard guard(session, {pub_key_handle, priv_key_handle});
470 std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle), PKCS11_RSA_PrivateKey(session, priv_key_handle));
#define BOTAN_ASSERT_NONNULL(ptr)
#define BOTAN_ARG_CHECK(expr, msg)
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)
std::optional< uint64_t > read()
Ulong checked_ulong_cast(size_t v)
CK_OBJECT_HANDLE ObjectHandle
CK_RSA_PKCS_PSS_PARAMS RsaPkcsPssParams
void require_hardware_provider(const OptionsT &options, std::string_view algo_name, std::string_view provider_name)
constexpr void copy_mem(T *out, const T *in, size_t n)
std::shared_ptr< const Montgomery_Exponentiation_State > monty_precompute(const Montgomery_Int &g, size_t window_bits)
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