Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Generate RSA Public/Private Key Pair and Export to PEM

See more RSA Examples

_LANGUAGE_ example code showing how to generate an RSA public/private key pair and export to PEM files.

Chilkat Rust Downloads

Rust

// 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.  Chilkat RSA supports
// key sizes ranging from 512 bits to 8192 bits.
let priv_key = chilkat::PrivateKey::new();
if rsa.gen_key(2048, &priv_key).is_err() {
    println!("{}", rsa.last_error_text());
    return;
}

let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);

// Save the private key in PEM format:
if priv_key.save_pem_file("privateKey.pem").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

// Save the public key in PEM format:
if pub_key.save_pem_file(false, "publicKey.pem").is_err() {
    println!("{}", pub_key.last_error_text());
    return;
}

println!("Success.");