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

RSA Encrypt and Decrypt Credit Card Numbers

See more RSA Examples

_LANGUAGE_ sample code to RSA public-key encrypt and decrypt credit card numbers. The RSA key is loaded from an unencrypted PKCS8 file. Chilkat provides many ways of setting the key -- loading from both encrypted and unencrypted PEM, PKCS8, DER, PVK, etc. Keys may be loaded from files or in-memory representations. (The RSA component also provides the ability to generate RSA keys.)

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

let priv_key = chilkat::PrivateKey::new();

// Load an RSA private key from a file:
if priv_key.load_any_format_file("rsaPrivateKey.key", "").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

// Get the public part of the private key.
let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);

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

// Encrypt a VISA credit card number:
// 1234-5678-0000-9999
let cc_number = "1234567800009999".to_string();

let mut use_private_key = false;
rsa.set_encoding_mode("base64");
let encrypted_str = rsa.encrypt_string_enc(&cc_number, use_private_key).unwrap_or_default();
println!("Encrypted:");
println!("{}", encrypted_str);

// Now decrypt:
let rsa_decryptor = chilkat::Rsa::new();

rsa_decryptor.set_encoding_mode("base64");
let _ = rsa_decryptor.use_private_key(&priv_key);

use_private_key = true;
let decrypted_str = rsa_decryptor.decrypt_string_enc(&encrypted_str, use_private_key).unwrap_or_default();

println!("Decrypted:");
println!("{}", decrypted_str);

// Important: RSA encryption should only be used to encrypt small amounts of data.
// It is typically used for encrypting symmetric encryption
// keys such that a symmetric encryption algorithm, such as 
// AES is then used to encrypt/decrypt bulk data.