Skip to content

how to: PK (asymmetric) EC

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

mbedcrypto supports elliptic curve (ec) as ecdsa and ecdh(e).

to create ec keys from curves:

using namespace mbedcrypto;

if ( supports(features::pk_export)  &&  supports(pk_t::eckey) ) {
    ecp gen; // elliptic curve public key infrastructure
    gen.generate_key(curve_t::secp224k1); // or any other supported curves
    auto pri_data = gen.export_key(pk::pem_format);
    auto pub_data = gen.export_public_key(pk::pem_format);
    // do stuff

    auto kinfo = gen.key_info(); // ecurve points and secret
    std::cout << "\nQx (" << kinfo.Qx.bitlen() << "): " << kinfo.Qx.to_string()
              << "\nQy (" << kinfo.Qy.bitlen() << "): " << kinfo.Qy.to_string()
              << "\nQz (" << kinfo.Qz.bitlen() << "): " << kinfo.Qz.to_string()
              << "\nd  (" << kinfo.D.bitlen() << "): " << kinfo.d.to_string()
              << std::endl;
}

to sign and verify by ecdsa:

using namespace mbedcrypto;

if ( supports(pk_t::ecdsa)  &&  supports(features::ec_keygen) ) {
    ecdsa pri_key; // both pk_t::eckey and pk_t::ecdsa works
    pri_key.generate_key(curve_t::secp192k1);
    auto sig = pri_key.sign_message(message, hash_t::sha384);

    ecdsa pub_key;
    pub_key.import_public_key(pri_key.export_public_key(pk::pem_format));

    REQUIRE(pub_key.verify_message(sig, message, hash_t::sha384));
}

to create a shared secret by ecdh(e) when both ends know the curve type:

using namespace mbedcrypto;
constexpr auto ctype = curve_t::secp224r1 // both ends know the curve type

// on server machine
ecdh server;
auto srv_pub = server.make_peer_key(ctype);
// send srv_pub to client

// on client machine
ecdh client;
client.generate_key(ctype); // alternative approach to make_peer_key()
auto cli_pub = client.peer_key();
// send cli_pub to server

auto sss = server.shared_secret(cli_pub); // on server machine
auto css = client.shared_secret(srv_pub); // on client machine

REQUIRE( (sss == css) ); 

or if the curve parameters are defined by server at runtime as defined in RFC 4492: Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS) do:

using namespace mbedcrypto;

// on server machine
ecdh server;
// (only) server defines the curve type
auto skex = server.make_server_key_exchange(curve_t::secp192k1);
// send server's key exchange params to client

// on client machine
ecdh client;
auto cli_pub = client.make_client_peer_key(skex);
auto css     = client.shared_secret();
// send cli_pub to server

// on server machine
auto sss = server.shared_secret(cli_pub); // on server

REQUIRE( (sss == css) );

see ecp.hpp

Clone this wiki locally