Rust
Rust
Get Public Key from CSR
See more CSR Examples
Demonstrates how to get the public key from a CSR.Chilkat Rust Downloads
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let pem = chilkat::Pem::new();
// No password is required. Pass an empty password string..
let no_password = String::new();
if pem.load_pem_file("qa_data/csr/csr2.pem", &no_password).is_err() {
println!("{}", pem.last_error_text());
return;
}
let str_base64 = pem.get_encoded_item("csr", "", "base64", 0).unwrap_or_default();
let asn = chilkat::Asn::new();
if asn.load_encoded(&str_base64, "base64").is_err() {
println!("{}", asn.last_error_text());
return;
}
// Convert the ASN.1 to XML.
let xml = chilkat::Xml::new();
let _ = xml.load_xml(&asn.asn_to_xml().unwrap_or_default()).is_ok();
println!("{}", xml.get_xml().unwrap_or_default());
println!("----");
let str_modulus_hex = xml.get_child_content("bits").unwrap_or_default();
println!("strModulusHex = {}", str_modulus_hex);
println!("----");
// We need the modulus as base64.
let bd = chilkat::BinData::new();
let _ = bd.append_encoded(&str_modulus_hex, "hex");
let modulus64 = bd.get_encoded("base64").unwrap_or_default();
println!("modulus64 = {}", modulus64);
println!("----");
// Build the XML for the public key.
let xml_pub_key = chilkat::Xml::new();
xml_pub_key.set_tag("RSAPublicKey");
xml_pub_key.update_child_content("Modulus", &modulus64);
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
xml_pub_key.update_child_content("Exponent", "AQAB");
println!("RSA public key as XML:");
println!("{}", xml_pub_key.get_xml().unwrap_or_default());
println!("----");
// Load the XML into a Chilkat public key object.
let pubkey = chilkat::PublicKey::new();
if pubkey.load_from_string(&xml_pub_key.get_xml().unwrap_or_default()).is_err() {
println!("{}", pubkey.last_error_text());
return;
}
// Show the public key as PEM.
let prefer_pkcs1 = true;
println!("{}", pubkey.get_pem(prefer_pkcs1).unwrap_or_default());