Expand description

Message encryption.

The Encrypter allows for encryption of data given a public key. The Decrypter can be used with the corresponding private key to decrypt the data.


Encrypt and decrypt data given an RSA keypair:

use openssl::encrypt::{Encrypter, Decrypter};
use openssl::rsa::{Rsa, Padding};
use openssl::pkey::PKey;

// Generate a keypair
let keypair = Rsa::generate(2048).unwrap();
let keypair = PKey::from_rsa(keypair).unwrap();

let data = b"hello, world!";

// Encrypt the data with RSA PKCS1
let mut encrypter = Encrypter::new(&keypair).unwrap();
// Create an output buffer
let buffer_len = encrypter.encrypt_len(data).unwrap();
let mut encrypted = vec![0; buffer_len];
// Encrypt and truncate the buffer
let encrypted_len = encrypter.encrypt(data, &mut encrypted).unwrap();

// Decrypt the data
let mut decrypter = Decrypter::new(&keypair).unwrap();
// Create an output buffer
let buffer_len = decrypter.decrypt_len(&encrypted).unwrap();
let mut decrypted = vec![0; buffer_len];
// Encrypt and truncate the buffer
let decrypted_len = decrypter.decrypt(&encrypted, &mut decrypted).unwrap();
assert_eq!(&*decrypted, data);


A type which decrypts data.

A type which encrypts data.