Rust Requires Chilkat v11.0.0+
Rust
RSA Encrypt and Decrypt Strings
See more RSA Examples
_LANGUAGE_ sample code to RSA public-key encrypt and decrypt strings using public and private keys.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();
// This example also generates the public and private
// keys to be used in the RSA encryption.
// Normally, you would generate a key pair once,
// and distribute the public key to your partner.
// Anything encrypted with the public key can be
// decrypted with the private key. The reverse is
// also true: anything encrypted using the private
// key can be decrypted using the public key.
// Generate a 2048-bit key. Chilkat RSA supports
// key sizes ranging from 512 bits to 4096 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);
let plain_text = "Encrypting and decrypting should be easy!".to_string();
// Start with a new RSA object to demonstrate that all we
// need are the keys previously exported:
let rsa_encryptor = chilkat::Rsa::new();
// Encrypted output is always binary. In this case, we want
// to encode the encrypted bytes in a printable string.
// Our choices are "hex", "base64", "url", "quoted-printable".
rsa_encryptor.set_encoding_mode("hex");
// We'll encrypt with the public key and decrypt with the private
// key.
let _ = rsa_encryptor.use_public_key(&pub_key).is_ok();
let mut use_private_key = false;
let encrypted_str = rsa_encryptor.encrypt_string_enc(&plain_text, use_private_key).unwrap_or_default();
println!("{}", encrypted_str);
// Now decrypt:
let rsa_decryptor = chilkat::Rsa::new();
rsa_decryptor.set_encoding_mode("hex");
let _ = rsa_decryptor.use_private_key(&priv_key).is_ok();
use_private_key = true;
let decrypted_str = rsa_decryptor.decrypt_string_enc(&encrypted_str, use_private_key).unwrap_or_default();
println!("{}", decrypted_str);