AES OFB in RustAES OFB (output feedback) is a stream cipher mode for AES. We have a cipher of \(P_{j}=C_{j}\oplus O_{j}\), \(O_{j}=E_{K}(I_{j})\) \(I_{j}=O_{j-1}\), \(I_{0}={\text{IV}}\), and the same operation to decrypt. It allows a block encryptor to create a stream encryptor. |
The outline code is:
use rand::thread_rng; use rand::Rng; use core::str; use std::env; use aes::Aes128; use ofb::Ofb; use ofb::cipher::{NewCipher, StreamCipher}; type AesOfb = Ofb; fn get_random_key16() -> [u8; 16]{ let mut arr = [0u8; 16]; thread_rng().try_fill(&mut arr[..]).expect("Ooops!"); return arr; } fn main() { let key=get_random_key16(); let iv=get_random_key16(); let mut msg = String::from("Hello world!"); let args: Vec = env::args().collect(); if args.len() >1 { msg = args[1].clone(); } let mut buffer=msg.as_bytes().to_vec(); let mut cipher = AesOfb::new_from_slices(&key, &iv).unwrap(); cipher.apply_keystream(&mut buffer); print!("Plaintext: {}\n", msg); println!("128-bit (16 byte) key: {}",hex::encode(key)); println!("IV: {}\n",hex::encode(iv)); print!("\nCipher: {}\n", hex::encode(buffer.clone())); AesOfb::new_from_slices(&key, &iv).unwrap().apply_keystream(&mut buffer); print!("Plaintext: {}\n", str::from_utf8(&buffer).unwrap()); }
and Cargo.toml:
[package] name = "randkey" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] hex="0.4.2" rand="0.8.3" aes="0.7.5" block-modes="0.8.1"
A test run is:
Plaintext: Hello 123 128-bit (16 byte) key: 3671954b7a21aae0e0735cf594bdd845 IV: eba28f540ba1778287d16e6dc70ec8e8 Cipher: 627d746bf90a23b759 Plaintext: Hello 123