feat: add __crypto/aes_ctr_test/

This commit is contained in:
2024-08-31 17:11:16 +08:00
parent 22344b6d96
commit 7f0e18bbe4
4 changed files with 180 additions and 1 deletions

View File

@@ -0,0 +1,70 @@
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{Block, BlockEncryptMut, KeyInit};
use aes::Aes128;
fn main() {
let key = [0_u8; 16];
let iv = [0_u8; 16];
let plaintext = b"hello world";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("0e8c27b880aa5b54fa209e", hex::encode(&ciphertext));
let plaintext = b"hello world.hello world.hello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("0e8c27b880aa5b54fa209e77a251474237c28ba18812544f5e1a713bcbc7323571e4bee008d3cf\
fe9c08b5d603de9a569ff0c6c7266b2e4c8591edd1fceead8c4f22664e3c1ff0f4", hex::encode(&ciphertext));
let key = [1_u8; 16];
let mut iv = [0_u8; 16];
for i in 0..8 {
iv[i] = i as u8 + 1;
}
let plaintext = b"hello world.hello world.hello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("84ad8d80732490c061177a58bd26d032d6fcff2e66f9afe3cf95717485d3a4485d4a2a7bd835df\
3d0756b8192e3bf5a287ad8dd81942c43bc812c82d666ebbb34df4e2a5069467d9", hex::encode(&ciphertext));
}
fn encrypt_ctr(key: &[u8; 16], iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
let mut aes128 = Aes128::new_from_slice(key).unwrap();
let plaintext_len = plaintext.len();
let blocks_count = (plaintext_len / 16) + if plaintext_len % 16 == 0 { 0 } else { 1 };
let mut iv = iv.clone();
let mut cipher_text = vec![0_u8; plaintext_len];
for i in 0..blocks_count {
update_ctr(&mut iv, i as u64);
let mut block: Block<Aes128> = GenericArray::from_slice(&iv).clone();
aes128.encrypt_block_mut(&mut block);
let block_slice = block.as_slice();
for j in 0..block_slice.len() {
let oi = i * 16 + j;
if oi < plaintext_len {
cipher_text[oi] = block_slice[j] ^ plaintext[oi];
}
}
}
cipher_text
}
fn update_ctr(iv: &mut [u8; 16], counter: u64) {
let counter_be_bytes = counter.to_be_bytes();
for i in 8..iv.len() {
iv[i] = counter_be_bytes[i - 8];
}
}
#[test]
fn test_aes() {
let mut aes128 = Aes128::new_from_slice(
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
).unwrap();
let mut a: Block<Aes128> = GenericArray::from_slice(&[0_u8; 16]).clone();
aes128.encrypt_block_mut(&mut a);
println!("{}", hex::encode(a.as_slice()));
assert_eq!("66e94bd4ef8a2c3b884cfa59ca342b2e", hex::encode(a.as_slice()));
}