Module openssl::cipher_ctx

source ·
Expand description

The symmetric encryption context.

§Examples

Encrypt data with AES128 CBC

use openssl::cipher::Cipher;
use openssl::cipher_ctx::CipherCtx;

let cipher = Cipher::aes_128_cbc();
let data = b"Some Crypto Text";
let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07";

let mut ctx = CipherCtx::new().unwrap();
ctx.encrypt_init(Some(cipher), Some(key), Some(iv)).unwrap();

let mut ciphertext = vec![];
ctx.cipher_update_vec(data, &mut ciphertext).unwrap();
ctx.cipher_final_vec(&mut ciphertext).unwrap();

assert_eq!(
    b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\x87\x4D\
      \xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1",
    &ciphertext[..],
);

Decrypt data with AES128 CBC

use openssl::cipher::Cipher;
use openssl::cipher_ctx::CipherCtx;

let cipher = Cipher::aes_128_cbc();
let data = b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\
             \x87\x4D\xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1";
let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07";

let mut ctx = CipherCtx::new().unwrap();
ctx.decrypt_init(Some(cipher), Some(key), Some(iv)).unwrap();

let mut plaintext = vec![];
ctx.cipher_update_vec(data, &mut plaintext).unwrap();
ctx.cipher_final_vec(&mut plaintext).unwrap();

assert_eq!(b"Some Crypto Text", &plaintext[..]);

Structs§