Created
May 30, 2023 20:02
-
-
Save 641i130/1c5b11429f5f4f2179dd60fb69b7995d to your computer and use it in GitHub Desktop.
rsa decrypt rust lang example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rsa-decrypt" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
openssl = "0.10.53" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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