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

RSA Encrypt with Modulus and Exponent

See more RSA Examples

Demonstrates how to RSA encrypt with a given modulus and exponent.

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();

// Assuming you already have a base64 modulus and exponent,
// wrap it in XML like this:
let modulus = "qMBRpdYrAy5aMmo31NErUizh5sbweguSmh4wlK6uJEIDl+kwTlROnE34KOFExeTbJSX0WygPi+vWl0yNq7buIMUKpytossAAWut5khO3CQJxTk7G2gnEPNUUXHiExGgNrLzcSLv8YIlfVALhoRWyC67KOL+a+3taNq3h+BHeWhM=".to_string();
let exponent = "AQAB".to_string();

let xml = chilkat::Xml::new();
xml.set_tag("RSAPublicKey");
xml.new_child2("Modulus", &modulus);
xml.new_child2("Exponent", &exponent);

let pub_key = chilkat::PublicKey::new();
if pub_key.load_from_string(&xml.get_xml().unwrap_or_default()).is_err() {
    println!("{}", pub_key.last_error_text());
    return;
}

if rsa.use_public_key(&pub_key).is_err() {
    println!("{}", rsa.last_error_text());
    return;
}

let use_private_key = false;
let plain_text = "message in a bottle".to_string();

rsa.set_encoding_mode("base64");
let encrypted_str_base64 = rsa.encrypt_string_enc(&plain_text, use_private_key).unwrap_or_default();
println!("{}", encrypted_str_base64);