Created
April 3, 2022 19:40
-
-
Save KerfuffleV2/d61e1b62a10f63e4553a64a586610972 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use aes::cipher::{ | |
generic_array::GenericArray, BlockCipher, BlockDecrypt, BlockEncrypt, KeyInit, KeySizeUser, | |
}; | |
use aes::{Aes128, Aes192}; | |
#[derive(Debug, Clone)] | |
struct Testy<CI> { | |
cipher: CI, | |
data: Vec<u8>, | |
} | |
trait CipherTraitBundle: BlockCipher + BlockEncrypt + BlockDecrypt + KeyInit + KeySizeUser {} | |
impl CipherTraitBundle for Aes128 {} | |
impl CipherTraitBundle for Aes192 {} | |
impl<CI: CipherTraitBundle> Testy<CI> { | |
pub fn new(key: GenericArray<u8, <CI as KeySizeUser>::KeySize>) -> Self { | |
Self { | |
cipher: <CI as KeyInit>::new(&key), | |
data: vec![], | |
} | |
} | |
pub fn encode(&mut self) { | |
self.cipher | |
.encrypt_block(GenericArray::from_mut_slice(self.data.as_mut_slice())); | |
} | |
pub fn decode(&self) -> Vec<u8> { | |
let mut output = self.data.clone(); | |
self.cipher | |
.decrypt_block(GenericArray::from_mut_slice(output.as_mut_slice())); | |
output | |
} | |
} | |
fn encode_any_testy<CI: CipherTraitBundle>(arg: &mut Testy<CI>) { | |
arg.encode(); | |
} | |
fn main() { | |
let mut x = Testy::<Aes128>::new(GenericArray::from([0u8; 16])); | |
x.data = (0..16).collect(); | |
println!("x: Before encode: {:?}", x); | |
encode_any_testy(&mut x); | |
let x_decoded = x.decode(); | |
println!("x: After encode: {:?} => {:?}", x, x_decoded); | |
let mut y = Testy::<Aes192>::new(GenericArray::from([0u8; 24])); | |
println!("y: Before encode: {:?}", y); | |
y.data = (0..16).collect(); | |
encode_any_testy(&mut y); | |
let y_decoded = y.decode(); | |
println!("y: After encode: {:?} => {:?}", y, y_decoded); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x: Before encode: Testy { cipher: Aes128 { .. }, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] } | |
x: After encode: Testy { cipher: Aes128 { .. }, data: [122, 202, 15, 217, 188, 214, 236, 124, 159, 151, 70, 102, 22, 230, 162, 130] } => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] | |
y: Before encode: Testy { cipher: Aes192 { .. }, data: [] } | |
y: After encode: Testy { cipher: Aes192 { .. }, data: [184, 26, 102, 73, 80, 0, 143, 145, 50, 62, 213, 59, 211, 48, 147, 41] } => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment