Rust Requires Chilkat v11.0.0+
Rust
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.Chilkat Rust Downloads
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;
}
let password = "secret".to_string();
// Saving to a relative path (from the current working directory of the process).
let mut path = "rsaKeys/myTestRsaPrivate.pem".to_string();
// Encrypt the PEM using 256-bit AES encryption.
priv_key.set_pkcs8_encrypt_alg("aes256");
if priv_key.save_pkcs8_encrypted_pem_file(&password, &path).is_err() {
println!("{}", priv_key.last_error_text());
return;
}
//
// We can also save the public key.
// There is no need to encrypt public keys.
let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);
path = "rsaKeys/myTestRsaPublic.pem".to_string();
// Choose PKCS1 or PKCS8
// We'll choose PKCS8.
let prefer_pkcs1 = false;
if pub_key.save_pem_file(prefer_pkcs1, &path).is_err() {
println!("{}", pub_key.last_error_text());
return;
}
//
println!("Success.");