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/pk_ops_impl.h>
25RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(
const BigInt& modulus,
const BigInt& pub_exponent) :
26 PublicKeyProperties(
KeyType::
Rsa), m_modulus(modulus), m_pub_exponent(pub_exponent) {
27 add_binary(AttributeType::Modulus, m_modulus.serialize());
28 add_binary(AttributeType::PublicExponent, m_pub_exponent.serialize());
31RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits) : PublicKeyProperties(
KeyType::
Rsa) {
32 add_numeric(AttributeType::ModulusBits, bits);
35PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle) :
36 Object(session, handle),
40PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session,
const RSA_PublicKeyImportProperties& pubkey_props) :
41 Object(session, pubkey_props), RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()) {}
43RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(
const BigInt& modulus,
const BigInt& priv_exponent) :
44 PrivateKeyProperties(
KeyType::
Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent) {
45 add_binary(AttributeType::Modulus, m_modulus.serialize());
46 add_binary(AttributeType::PrivateExponent, m_priv_exponent.serialize());
49PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle) :
50 Object(session, handle),
54PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
const RSA_PrivateKeyImportProperties& priv_key_props) :
55 Object(session, priv_key_props),
58PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
60 const RSA_PrivateKeyGenerationProperties& priv_key_props) :
61 Object(session), RSA_PublicKey() {
62 RSA_PublicKeyGenerationProperties pub_key_props(bits);
63 pub_key_props.set_encrypt(
true);
64 pub_key_props.set_verify(
true);
65 pub_key_props.set_token(
false);
70 session.module()->C_GenerateKeyPair(session.handle(),
73 static_cast<Ulong>(pub_key_props.count()),
74 priv_key_props.data(),
75 static_cast<Ulong>(priv_key_props.count()),
79 this->reset_handle(priv_key_handle);
81 BigInt n = BigInt::from_bytes(get_attribute_value(AttributeType::Modulus));
82 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
83 RSA_PublicKey::init(std::move(n), std::move(e));
86RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key()
const {
87 auto p = get_attribute_value(AttributeType::Prime1);
88 auto q = get_attribute_value(AttributeType::Prime2);
89 auto e = get_attribute_value(AttributeType::PublicExponent);
90 auto d = get_attribute_value(AttributeType::PrivateExponent);
91 auto n = get_attribute_value(AttributeType::Modulus);
93 return RSA_PrivateKey(BigInt::from_bytes(p),
94 BigInt::from_bytes(q),
95 BigInt::from_bytes(e),
96 BigInt::from_bytes(d),
97 BigInt::from_bytes(n));
100std::unique_ptr<Public_Key> PKCS11_RSA_PrivateKey::public_key()
const {
101 return std::make_unique<RSA_PublicKey>(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
102 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent)));
105secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits()
const {
106 return export_key().private_key_bits();
112class PKCS11_RSA_Decryption_Operation
final :
public PK_Ops::Decryption {
114 PKCS11_RSA_Decryption_Operation(
const PKCS11_RSA_PrivateKey& key,
115 std::string_view padding,
116 RandomNumberGenerator& rng) :
118 m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)),
119 m_barrett_mod_n(Modular_Reducer::for_public_modulus(m_key.get_n())),
123 [this](const BigInt& k) {
return power_mod(k, m_key.get_e(), m_key.get_n()); },
125 m_bits = m_key.get_n().bits() - 1;
128 size_t plaintext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
130 secure_vector<uint8_t>
decrypt(uint8_t& valid_mask, std::span<const uint8_t> ctext)
override {
132 m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
134 std::vector<uint8_t> encrypted_data(ctext.begin(), ctext.end());
136 const size_t modulus_bytes = (m_key.get_n().bits() + 7) / 8;
139 const bool use_blinding = !m_mechanism.padding_size();
142 const BigInt blinded = m_blinder.blind(BigInt::from_bytes(encrypted_data));
144 encrypted_data = blinded.serialize(modulus_bytes);
147 secure_vector<uint8_t> decrypted_data;
148 m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
152 const BigInt unblinded = m_blinder.unblind(BigInt::from_bytes(decrypted_data));
153 decrypted_data.resize(modulus_bytes);
154 unblinded.serialize_to(decrypted_data);
158 return decrypted_data;
162 const PKCS11_RSA_PrivateKey& m_key;
163 MechanismWrapper m_mechanism;
164 Modular_Reducer m_barrett_mod_n;
171class PKCS11_RSA_Decryption_Operation_Software_EME
final :
public PK_Ops::Decryption_with_EME {
173 PKCS11_RSA_Decryption_Operation_Software_EME(
const PKCS11_RSA_PrivateKey& key,
174 std::string_view padding,
175 RandomNumberGenerator& rng) :
176 PK_Ops::Decryption_with_EME(padding), m_raw_decryptor(key, rng,
"Raw") {}
178 size_t plaintext_length(
size_t ctext_len)
const override {
return m_raw_decryptor.plaintext_length(ctext_len); }
180 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input)
override {
181 return m_raw_decryptor.decrypt(input);
185 PK_Decryptor_EME m_raw_decryptor;
190class PKCS11_RSA_Encryption_Operation
final :
public PK_Ops::Encryption {
192 PKCS11_RSA_Encryption_Operation(
const PKCS11_RSA_PublicKey& key, std::string_view padding) :
193 m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(padding)) {
194 m_bits = 8 * (key.get_n().bytes() - m_mechanism.padding_size()) - 1;
197 size_t ciphertext_length(
size_t )
const override {
return m_key.get_n().bytes(); }
199 size_t max_input_bits()
const override {
return m_bits; }
201 std::vector<uint8_t>
encrypt(std::span<const uint8_t> input, RandomNumberGenerator& )
override {
202 m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
204 std::vector<uint8_t> encrypted_data;
205 m_key.module()->C_Encrypt(
206 m_key.session().handle(), secure_vector<uint8_t>(input.begin(), input.end()), encrypted_data);
207 return encrypted_data;
211 const PKCS11_RSA_PublicKey& m_key;
212 MechanismWrapper m_mechanism;
216class PKCS11_RSA_Signature_Operation
final :
public PK_Ops::Signature {
218 PKCS11_RSA_Signature_Operation(
const PKCS11_RSA_PrivateKey& key, std::string_view padding) :
219 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
221 size_t signature_length()
const override {
return m_key.get_n().bytes(); }
223 void update(std::span<const uint8_t> input)
override {
226 m_key.module()->C_SignInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
227 m_initialized =
true;
228 m_first_message.assign(input.begin(), input.end());
232 if(!m_first_message.empty()) {
234 m_key.module()->C_SignUpdate(m_key.session().handle(), m_first_message);
235 m_first_message.clear();
238 m_key.module()->C_SignUpdate(m_key.session().handle(), input.data(),
static_cast<Ulong>(input.size()));
241 std::vector<uint8_t> sign(RandomNumberGenerator& )
override {
242 std::vector<uint8_t> signature;
243 if(!m_first_message.empty()) {
245 m_key.module()->C_Sign(m_key.session().handle(), m_first_message, signature);
246 m_first_message.clear();
249 m_key.module()->C_SignFinal(m_key.session().handle(), signature);
251 m_initialized =
false;
255 std::string hash_function()
const override;
257 AlgorithmIdentifier algorithm_identifier()
const override;
260 PKCS11_RSA_PrivateKey m_key;
261 bool m_initialized =
false;
262 secure_vector<uint8_t> m_first_message;
263 MechanismWrapper m_mechanism;
268std::string hash_function_name_from_pkcs11_rsa_mechanism_type(MechanismType type) {
270 case MechanismType::Sha1RsaPkcs:
271 case MechanismType::Sha1RsaPkcsPss:
272 case MechanismType::Sha1RsaX931:
275 case MechanismType::Sha224RsaPkcs:
276 case MechanismType::Sha224RsaPkcsPss:
279 case MechanismType::Sha256RsaPkcs:
280 case MechanismType::Sha256RsaPkcsPss:
283 case MechanismType::Sha384RsaPkcs:
284 case MechanismType::Sha384RsaPkcsPss:
287 case MechanismType::Sha512RsaPkcs:
288 case MechanismType::Sha512RsaPkcsPss:
291 case MechanismType::RsaX509:
292 case MechanismType::RsaX931:
293 case MechanismType::RsaPkcs:
294 case MechanismType::RsaPkcsPss:
298 throw Internal_Error(
"Unable to determine associated hash function of PKCS11 RSA signature operation");
304std::string PKCS11_RSA_Signature_Operation::hash_function()
const {
305 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
308AlgorithmIdentifier PKCS11_RSA_Signature_Operation::algorithm_identifier()
const {
309 const std::string hash = this->hash_function();
311 switch(m_mechanism.mechanism_type()) {
312 case MechanismType::Sha1RsaPkcs:
313 case MechanismType::Sha224RsaPkcs:
314 case MechanismType::Sha256RsaPkcs:
315 case MechanismType::Sha384RsaPkcs:
316 case MechanismType::Sha512RsaPkcs: {
317 const OID oid = OID::from_string(
"RSA/EMSA3(" + hash +
")");
318 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
321 case MechanismType::Sha1RsaPkcsPss:
322 case MechanismType::Sha224RsaPkcsPss:
323 case MechanismType::Sha256RsaPkcsPss:
324 case MechanismType::Sha384RsaPkcsPss:
325 case MechanismType::Sha512RsaPkcsPss:
326 throw Not_Implemented(
"RSA-PSS identifier encoding missing for PKCS11");
329 throw Not_Implemented(
"No algorithm identifier defined for RSA with this PKCS11 mechanism");
333class PKCS11_RSA_Verification_Operation
final :
public PK_Ops::Verification {
335 PKCS11_RSA_Verification_Operation(
const PKCS11_RSA_PublicKey& key, std::string_view padding) :
336 m_key(key), m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(padding)) {}
338 void update(std::span<const uint8_t> input)
override {
341 m_key.module()->C_VerifyInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
342 m_initialized =
true;
343 m_first_message.assign(input.begin(), input.end());
347 if(!m_first_message.empty()) {
349 m_key.module()->C_VerifyUpdate(m_key.session().handle(), m_first_message);
350 m_first_message.clear();
353 m_key.module()->C_VerifyUpdate(m_key.session().handle(), input.data(),
static_cast<Ulong>(input.size()));
356 bool is_valid_signature(std::span<const uint8_t> sig)
override {
357 ReturnValue return_value = ReturnValue::SignatureInvalid;
358 if(!m_first_message.empty()) {
360 m_key.module()->C_Verify(m_key.session().handle(),
361 m_first_message.data(),
362 static_cast<Ulong>(m_first_message.size()),
364 static_cast<Ulong>(sig.size()),
366 m_first_message.clear();
369 m_key.module()->C_VerifyFinal(
370 m_key.session().handle(), sig.data(),
static_cast<Ulong>(sig.size()), &return_value);
372 m_initialized =
false;
373 if(return_value != ReturnValue::OK && return_value != ReturnValue::SignatureInvalid) {
374 throw PKCS11_ReturnError(return_value);
376 return return_value == ReturnValue::OK;
379 std::string hash_function()
const override;
382 const PKCS11_RSA_PublicKey m_key;
383 bool m_initialized =
false;
384 secure_vector<uint8_t> m_first_message;
385 MechanismWrapper m_mechanism;
388std::string PKCS11_RSA_Verification_Operation::hash_function()
const {
389 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
394std::unique_ptr<PK_Ops::Encryption> PKCS11_RSA_PublicKey::create_encryption_op(RandomNumberGenerator& ,
395 std::string_view params,
396 std::string_view )
const {
397 return std::make_unique<PKCS11_RSA_Encryption_Operation>(*
this, params);
400std::unique_ptr<PK_Ops::Verification> PKCS11_RSA_PublicKey::create_verification_op(
401 std::string_view params, std::string_view )
const {
402 return std::make_unique<PKCS11_RSA_Verification_Operation>(*
this, params);
405std::unique_ptr<PK_Ops::Decryption> PKCS11_RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
406 std::string_view params,
407 std::string_view )
const {
408 if(params !=
"Raw" && m_use_software_padding) {
409 return std::make_unique<PKCS11_RSA_Decryption_Operation_Software_EME>(*
this, params, rng);
411 return std::make_unique<PKCS11_RSA_Decryption_Operation>(*
this, params, rng);
415std::unique_ptr<PK_Ops::Signature> PKCS11_RSA_PrivateKey::create_signature_op(RandomNumberGenerator& ,
416 std::string_view params,
417 std::string_view )
const {
418 return std::make_unique<PKCS11_RSA_Signature_Operation>(*
this, params);
421PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session,
422 const RSA_PublicKeyGenerationProperties& pub_props,
423 const RSA_PrivateKeyGenerationProperties& priv_props) {
429 session.module()->C_GenerateKeyPair(session.handle(),
432 static_cast<Ulong>(pub_props.count()),
434 static_cast<Ulong>(priv_props.count()),
438 return std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle),
439 PKCS11_RSA_PrivateKey(session, priv_key_handle));
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)
std::string decrypt(const uint8_t input[], size_t input_len, std::string_view passphrase)
CK_OBJECT_HANDLE ObjectHandle
BigInt power_mod(const BigInt &base, const BigInt &exp, const BigInt &mod)
BigInt inverse_mod_rsa_public_modulus(const BigInt &x, const BigInt &n)
#define CK_INVALID_HANDLE
CK_ULONG CK_MECHANISM_TYPE