Skip to content

how to: PK (asymmetric) RSA

amir zamani edited this page Aug 5, 2016 · 1 revision

to import or load an RSA key:

using namespace mbedcrypto;

rsa pri_key;
// import from data buffer
pri_key.import_key(private_key_data, optional_password);
// or load from a file by file-name
pri_key.load_key("private_key.pem");

rsa pub_key;
pub_key.import_public_key(public_key_data);

// [optional] check matching public/private pair
REQUIRE( check_pair(pub_key, pri_key) == true );

exporting:

// export keys
if ( supports(features::pk_export) ) {
    auto der_data = pub_key.export_public_key(pk::der_format);
    // write or share
}

generating new rsa keys:

// key generation
if ( supports(features::rsa_keygen) ) {
    rsa pri_key;
    pri_key.generate_key(2048); // a 2048bit key
    // do stuff
}

to check what an rsa key can do:

auto af = pub_key.what_can_do(); // what can i do with this key?
// returns pk::action_flags (key capabilities) with following data:
// af.encrypt = true
// af.decrypt = false
// af.sign    = false
// af.verify  = true
// because pub_key is a valid rsa public-key

auto kinfo = pri_key.key_info();
// kinfo.N  :  public modulus
// kinfo.E  :  public exponent
// only valid if the key is a private key
// kinfo.D  :  private exponent
// kinfo.P  :  1st prime factor
// kinfo.Q  :  2nd prime factor
// kinfo.DP  : D % (P - 1)
// kinfo.DQ  : D % (Q - 1)
// kinfo.QP  : 1 / (Q % P)

to sign and verify by rsa:

constexpr auto hash_type = hash_t:sha256;
// signature & verification
std::string message = read_message_from_somewhere();
auto signature      = pri_key.sign_message(message, hash_type);
REQUIRE( pub_key.verify_message(signature, message, hash_type);

to encrypt and decrypt by rsa:

const auto hvalue = hash::make(hash_type, message);
auto encv = pub_key.encrypt(hvalue);
auto decv = pri_key.decrypt(encv);
REQUIRE( decv == hvalue );

see rsa.hpp

Clone this wiki locally