Crate block_modes[][src]

This crate contains generic implementation of block cipher modes of operation.

Note that some block modes (such as CTR, CFB, and OFB) transform block ciphers into stream ciphers. Implementations in this crate require padding, so if you want use those modes as stream ciphers (i.e. without padding), then check out crates in the RustCrypto/stream-ciphers repository.

Usage example

use aes::Aes128;
use block_modes::{BlockMode, Cbc};
use block_modes::block_padding::Pkcs7;
use hex_literal::hex;

// create an alias for convenience
type Aes128Cbc = Cbc<Aes128, Pkcs7>;

let key = hex!("000102030405060708090a0b0c0d0e0f");
let iv = hex!("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
let plaintext = b"Hello world!";
let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();

// buffer must have enough space for message+padding
let mut buffer = [0u8; 32];
// copy message to the buffer
let pos = plaintext.len();
buffer[..pos].copy_from_slice(plaintext);
let ciphertext = cipher.encrypt(&mut buffer, pos).unwrap();

assert_eq!(ciphertext, hex!("1b7a4c403124ae2fb52bedc534d82fa8"));

// re-create cipher mode instance
let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();
let mut buf = ciphertext.to_vec();
let decrypted_ciphertext = cipher.decrypt(&mut buf).unwrap();

assert_eq!(decrypted_ciphertext, plaintext);

With an enabled alloc feature (which is enabled by default) you can use encrypt_vec and descrypt_vec methods:

let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();
let ciphertext = cipher.encrypt_vec(plaintext);

assert_eq!(ciphertext, hex!("1b7a4c403124ae2fb52bedc534d82fa8"));

let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();
let decrypted_ciphertext = cipher.decrypt_vec(&ciphertext).unwrap();

assert_eq!(decrypted_ciphertext, plaintext);

Re-exports

pub use block_padding;
pub use cipher;

Structs

BlockModeError

Block mode error.

Cbc

Cipher Block Chaining (CBC) block cipher mode instance.

Cfb

Cipher feedback (CFB) block mode instance with a full block feedback.

Cfb8

Cipher feedback (CFB) block mode instance with a full block feedback.

Ecb

Electronic Codebook (ECB) block cipher mode instance.

Ige

Infinite Garble Extension (IGE) block cipher mode instance.

InvalidKeyIvLength

Invalid key or IV length error.

Ofb

Output feedback (OFB) block mode instance with a full block feedback.

Pcbc

Propagating Cipher Block Chaining (PCBC) mode instance.

Traits

BlockMode

Trait for a block cipher mode of operation that is used to apply a block cipher operation to input data to transform it into a variable-length output message.

IvState

Trait for a BlockMode, used to obtain the current state in the form of an IV that can initialize a BlockMode later and resume the original operation.