Crate ctr

source · []
Expand description

Generic implementations of CTR mode for block ciphers.

Mode functionality is accessed using traits from re-exported cipher crate.

⚠️ Security Warning: Hazmat!

This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity is not verified, which can lead to serious vulnerabilities!


use aes::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
use hex_literal::hex;

type Aes128Ctr64LE = ctr::Ctr64LE<aes::Aes128>;

let key = [0x42; 16];
let iv = [0x24; 16];
let plaintext = *b"hello world! this is my plaintext.";
let ciphertext = hex!(

// encrypt in-place
let mut buf = plaintext.to_vec();
let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into());
cipher.apply_keystream(&mut buf);
assert_eq!(buf[..], ciphertext[..]);

// CTR mode can be used with streaming messages
let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into());
for chunk in buf.chunks_mut(3) {
assert_eq!(buf[..], plaintext[..]);

// CTR mode supports seeking. The parameter is zero-based _bytes_ counter (not _blocks_).

// encrypt/decrypt from buffer to buffer
// buffer length must be equal to input length
let mut buf1 = [0u8; 34];
    .apply_keystream_b2b(&plaintext, &mut buf1)
assert_eq!(buf1[..], ciphertext[..]);

let mut buf2 = [0u8; 34];
cipher.apply_keystream_b2b(&buf1, &mut buf2).unwrap();
assert_eq!(buf2[..], plaintext[..]);


pub use cipher;
pub use flavors::CtrFlavor;


CTR mode flavors


Generic CTR block mode instance.

Type Definitions

CTR mode with 32-bit big endian counter.
CTR mode with 32-bit little endian counter.
CTR mode with 64-bit big endian counter.
CTR mode with 64-bit little endian counter.
CTR mode with 128-bit big endian counter.
CTR mode with 128-bit little endian counter.