Rust Requires Chilkat v11.0.0+
Rust
Generate an RSA Key and Get as Base64 DER
See more RSA Examples
Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.Chilkat Rust Downloads
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let rsa = chilkat::Rsa::new();
// Generate a 2048-bit key.
let priv_key = chilkat::PrivateKey::new();
if rsa.gen_key(2048, &priv_key).is_err() {
println!("{}", rsa.last_error_text());
return;
}
// Get the public part of the key.
let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);
// There are two possible formats for representing the RSA public key
// in ASN.1 (DER). The possible formats are PKCS1 and PKCS8.
// We can get either by setting bChoosePkcs1 to true or false.
let b_choose_pkcs1 = true;
let pub_key_base64_der = pub_key.get_encoded(b_choose_pkcs1, "base64").unwrap_or_default();
println!("Public Key Base64 DER:");
println!("{}", pub_key_base64_der);
// Get the private key as Base64 DER:
// We can get PKCS1 or PKCS8, but with different methods:
let priv_key_pkcs1 = priv_key.get_pkcs1_enc("base64").unwrap_or_default();
println!("Private Key PKCS1 Base64 DER:");
println!("{}", priv_key_pkcs1);
let priv_key_pkcs8 = priv_key.get_pkcs8_enc("base64").unwrap_or_default();
println!("Private Key PKCS8 Base64 DER:");
println!("{}", priv_key_pkcs8);