Header Ads

Rust encrypt with rsa public key

 Rust encrypt with RSA public key

Rust encrypt with RSA public key

We use cargo to build this example.

Require modules:

rsa = "0.5.0"

rand = "0.8.4"

My code to show, How to encrypt, decrypt with RSA



name = "algorithm"

version = "0.1.0"

edition = "2021"


rsa = "0.5.0"

rand = "0.8.4"


use rand::rngs::OsRng;
use rsa::{PaddingScheme, PublicKey, RsaPrivateKey, RsaPublicKey};

pub fn main() {
let mut rng = OsRng;
let bits = 512;
let private_key = RsaPrivateKey::new(&mut rng, bits)         .expect("failed to generate a key");
let public_key = RsaPublicKey::from(&private_key);

// Encrypt
let plain_text = b"Hello world!";
let cipher_text = public_key
&mut rng,
.expect("failed to encrypt");
println!("Cipher Text: {:?}", cipher_text);

// Decrypt
let decrypted_text = private_key
.decrypt(             PaddingScheme::new_pkcs1v15_encrypt(),             &cipher_text)
.expect("failed to decrypt");

println!(         "Plain text: {}",         String::from_utf8_lossy(&decrypted_text)         );


No comments