Sample code for 30+ languages & platforms
Rust

Get ECC Public Key in JWK Format (JSON Web Key)

See more ECC Examples

Demonstrates how to get an ECC public key in JWK (JSON Web Key) format.

Note: This example requires Chilkat v9.5.0.66 or later.

Chilkat Rust Downloads

Rust

// Note: This example requires Chilkat v9.5.0.66 or later.

// Load a PEM file into memory.
let sb_pem = chilkat::StringBuilder::new();
if sb_pem.load_file("qa_data/pem/ecc_public.pem", "utf-8").is_err() {
    println!("Failed to load PEM file.");
    return;
}

// Load the PEM into a public key object.
let pub_key = chilkat::PublicKey::new();
if pub_key.load_from_string(&sb_pem.get_as_string().unwrap_or_default()).is_err() {
    println!("{}", pub_key.last_error_text());
    return;
}

// Get the public key in JWK format:
let jwk = pub_key.get_jwk().unwrap_or_default();

// The GetJwk method will return the JWK in the most compact JSON format possible,
// as a single line with no extra whitespace.  To get a more human-readable JWK (for this example),
// load into a Chilkat JSON object and emit non-compact:

let json = chilkat::JsonObject::new();
let _ = json.load(&jwk);
json.set_emit_compact(false);
println!("ECC Public Key in JWK format:");
println!("{}", json.emit().unwrap_or_default());

// Sample output:
// { 
//   "kty": "EC",
//   "crv": "P-256",
//   "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
//   "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU"
// }
// 
// Additional information can be added like this:
let _ = json.append_string("use", "enc");
let _ = json.append_string("kid", "123ABC");

// Now examine the JSON:
println!("{}", json.emit().unwrap_or_default());

// { 
//   "kty": "EC",
//   "crv": "P-256",
//   "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
//   "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU",
//   "use": "enc",
//   "kid": "123ABC"
// }