Skip to content

Instantly share code, notes, and snippets.

Created May 30, 2023 20:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
rsa decrypt rust lang example
name = "rsa-decrypt"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at
openssl = "0.10.53"
use openssl::rsa::{Padding, Rsa};
use std::fs::File;
use std::io::Read;
use std::str;
fn main() {
// Read the private key from a PEM file
let mut key_file = File::open("priv.pem").unwrap();
let mut key_buffer = Vec::new();
key_file.read_to_end(&mut key_buffer).unwrap();
// Load the private key from the PEM data
let rsa = Rsa::private_key_from_pem(&key_buffer).unwrap();
let data = b"foobar";
let mut buf = vec![0; rsa.size() as usize];
let encrypted_len = rsa.public_encrypt(data, &mut buf, Padding::PKCS1).unwrap();
let mut decrypted_buf = vec![0; rsa.size() as usize];
let decrypted_len = rsa.private_decrypt(&buf[..encrypted_len], &mut decrypted_buf, Padding::PKCS1).unwrap();
let decrypted_data = &decrypted_buf[..decrypted_len];
println!("Decrypted data: {:?}", str::from_utf8(decrypted_data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment