1
votes

I'm just starting out with rust and playing with a toy encryption library following docs at https://docs.rs/openssl/0.10.28/openssl/. I'd like to generate an elliptic-curve private+public keypair and print them in der or pem formats. I found it pretty straightforward to do with the private key

use openssl::ec::{EcKey,EcGroup};
use openssl::nid::Nid;

pub fn generate_keypair() {
    let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
    let key = EcKey::generate(&group).unwrap();
    println!("{:?}", key.private_key_to_der().unwrap()); // can use pem instead and print as utf8-string
}

However there doesn't seem to be any method like public_key_to_der for EcKey to export a public key, even debug-printing it doesn't work:

let public = key.public_key();
println!("{:?}", public);

gives a compilation error

openssl::ec::EcPointRef` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
2

2 Answers

1
votes

Ok, looks like I need to wrap it in PKey first using pkey::from_ec_key.

0
votes
use openssl::ec::{EcKey,EcGroup, EcPoint};
use openssl::nid::Nid;

fn key_from_public_key() {

    let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
    let key = EcKey::generate(&group).unwrap();
    let mut ctx = openssl::bn::BigNumContext::new().unwrap();

    println!("private eckey = {:?}", key.private_key());

    let bytes = key.public_key().to_bytes(&group,
        openssl::ec::PointConversionForm::COMPRESSED, &mut ctx).unwrap();

    println!("public key = {:?}", bytes);

    drop(key);
    let public_key = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap();
    let ec_key = EcKey::from_public_key(&group, &public_key).unwrap();

    assert!(ec_key.check_key().is_ok());

}