Symmetric key encryption uses the same key to encrypt and decrypt. It is mainly a block cipher with a block size of 128 bits. In this case we will use the ECB (Electronic Codebook) mode. Within ECB, we do not use a salt value, so that the IV (Initialisation Vector) value is ignored when we pass it. In this case we will use Rust to implement 128-bit AES with ECB mode.
AES ECB in Rust |
Code
First we create the with:
cargo new aes2
We then go into the aes2 folder, and add the following to the cargo.toml file:
[package] name = "my-project" version = "0.1.0" authors = ["runner"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] aes="0.7.5" hex="0.4.3" block-modes="0.8.1" hex-literal="0.3.3"
In this case we will use AES ECB with a 128-bit key. Notice we do not set the IV value, as it will be ignored in ECB:
use aes::Aes128; use block_modes::{BlockMode, Ecb}; use block_modes::block_padding::Pkcs7; use hex_literal::hex; use std::str; use std::env; type Aes128Ecb = Ecb<Aes128, Pkcs7>; fn main() { let iv = hex!(""); let mut message = String::from("Hello world!"); let mut mykey =String::from("000102030405060708090A0B0C0D0E0F"); let args: Vec<String> = env::args().collect(); if args.len() >1 { message = args[1].clone(); } if args.len() >2 { mykey = args[2].clone(); } println!("Message: {}",message); println!("Key: {}",mykey); let plaintext=message.as_bytes(); let key = hex::decode(mykey).expect("Decoding failed"); let cipher = Aes128Ecb::new_from_slices(&key, &iv).unwrap(); let pos = plaintext.len(); let mut buffer = [0u8; 128]; buffer[..pos].copy_from_slice(plaintext); let ciphertext = cipher.encrypt(&mut buffer, pos).unwrap(); println!("\nCiphertext: {:?}",hex::encode(ciphertext)); let cipher = Aes128Ecb::new_from_slices(&key,&iv).unwrap(); let mut buf = ciphertext.to_vec(); let decrypted_ciphertext = cipher.decrypt(&mut buf).unwrap(); println!("\nCiphertext: {:?}",str::from_utf8(decrypted_ciphertext).unwrap()); }
Finally we simply build with:
cargo build
A sample run is:
Message: Hello World! Key: 000102030405060708090A0B0C0D0E0F Ciphertext: "e9582a980228381bc56bf6541bf63484" Ciphertext: "Hello World!"