Botan Loading Existing RSA Private Key


I am using Botan C++ library to sign and verify some license.ini file. I have set up Botan PK_Signer to work with RSA algorithm for encrypting the hash created with PKCS v1.5. This is my code:

uint8_t private_key[] = "private key I already have generated."

// Read file content that needs to be signed.
std::string licensePath = argv[1];
std::string fileContents = readFileContent(licensePath);

// Prepare Botan RSA signer. PKCS1 v1.5 is used.
Botan::AutoSeeded_RNG rng;
Botan::secure_vector<uint8_t> secure_key_vector(private_key, private_key + sizeof(private_key) / sizeof(private_key[0]));

Botan::RSA_PrivateKey rsa_priv_key(Botan::AlgorithmIdentifier(), secure_key_vector);

Botan::PK_Signer signer(rsa_priv_key, rng, "EMSA-PKCS1-v1_5");

// Create signature.
std::vector<uint8_t> signature = signer.signature(rng);
std::string hexSignature = Botan::hex_encode(signature);

Marked line for generating RSA_PrivateKey object throws an exception:

Exception thrown at 0x00007FF85D2BC3C7 (vcruntime140.dll) in license_signer.exe: 0xC0000005: Access violation reading location 0x0000021A8FA07000.

I have never before used Botan library. If anyone have any idea why is this happening or idea how to implement this, please assist. Thanks.


2 Answers


private_key data going into the constructor you're trying to use must be DER encoded. Make sure it is. In general, however, you are probably better off using the appropriate loadKey method.

answered on Stack Overflow Apr 12, 2018 by mnistic

Using Botan 2.12.1

#include <string>
#include <botan/auto_rng.h>
#include <botan/auto_rng.h>
#include <botan/base64.h>
#include <botan/pkcs8.h>
#include <botan/rsa.h>
#include <botan/x509_key.h>
#include <botan/data_src.h>
#include <botan/pubkey.h>

//Assuming the private and public keys are in Base64 encoded BER.

Botan::AutoSeeded_RNG rng;
Botan::RSA_PrivateKey keyPair(rng, static_cast<size_t>(4096));
std::string privateKey = Botan::base64_encode(Botan::PKCS8::BER_encode(keyPair));
std::string publicKey = Botan::base64_encode(Botan::X509::BER_encode(keyPair));

//Loading the public key

Botan::SecureVector<uint8_t> keyBytes(Botan::base64_decode(publicKey));
std::unique_ptr<Botan::Public_Key> pbk(Botan::X509::load_key(std::vector(keyBytes.begin(), keyBytes.end())));

//Loading the private key

Botan::SecureVector<uint8_t> keyBytes(Botan::base64_decode(privateKey));
Botan::DataSource_Memory source(keyBytes);
std::unique_ptr<Botan::Private_Key> pvk(Botan::PKCS8::load_key(source));
answered on Stack Overflow Mar 7, 2020 by Joma • edited Mar 7, 2020 by Joma

User contributions licensed under CC BY-SA 3.0