use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt, KeyInit};
use aes::Aes128;
use std::mem;
pub fn xor_encrypt_decrypt(input: &[u8], key: &str) -> Vec<u8> {
let mut b_arr = Vec::with_capacity(input.len());
for (i, &byte) in input.iter().enumerate() {
b_arr.push(byte ^ key.as_bytes()[i % key.len()]);
}
b_arr
}
pub fn u64_to_u8_array(value: u64) -> [u8; 8] {
let bytes = value.to_ne_bytes();
let mut _result = [0; 8];
unsafe {
_result = mem::transmute_copy(&bytes);
}
_result
}
pub fn print_hex(data: &[u8], offset: u64) {
for (i, chunk) in data.chunks(20).enumerate() {
print!("{:08} | ", offset + 20 * i as u64);
for (j, &byte) in chunk.iter().enumerate() {
let color = if j % 2 == 0 { "\x1b[94m" } else { "\x1b[92m" };
print!("{}{:02X} \x1b[0m", color, byte);
}
print!("| ");
for byte_chunk in chunk.chunks(4) {
for byte in byte_chunk {
print!(
"{}",
if byte.is_ascii() && byte.is_ascii_graphic() {
*byte as char
} else {
'.'
}
);
}
}
println!();
}
}
pub fn pad_with_zeros(slice: &[u8]) -> [u8; 16] {
let mut padded_array: [u8; 16] = [0; 16];
let len = std::cmp::min(slice.len(), padded_array.len());
padded_array[..len].copy_from_slice(&slice[..len]);
padded_array
}
pub fn encrypt_payload(key: &str, payload: &str) -> Vec<u8> {
let in_key: &[u8; 16] = &pad_with_zeros(key.as_bytes());
let key = GenericArray::clone_from_slice(in_key);
if payload.len() <= 16 {
let in_payload: &[u8; 16] = &pad_with_zeros(payload.as_bytes());
let mut block = GenericArray::clone_from_slice(in_payload);
let cipher = Aes128::new(&key);
cipher.encrypt_block(&mut block);
block.to_vec()
} else {
let mut encrypted_data: Vec<u8> = Vec::new();
for (i, chunk) in payload.as_bytes().chunks_exact(16).enumerate() {
let in_payload: &[u8; 16] = &pad_with_zeros(chunk);
let mut block = GenericArray::clone_from_slice(in_payload);
let cipher = Aes128::new(&key);
cipher.encrypt_block(&mut block);
if i > 0 {
encrypted_data.extend_from_slice(&block);
} else {
encrypted_data = block.to_vec();
}
}
encrypted_data
}
}
pub fn decrypt_data(key: &str, data: &[u8]) -> Vec<u8> {
let in_key: &[u8; 16] = &pad_with_zeros(key.as_bytes());
let key = GenericArray::clone_from_slice(in_key);
let mut decrypted_data: Vec<u8> = Vec::new();
for (i, chunk) in data.chunks_exact(16).enumerate() {
let in_payload: &[u8; 16] = &pad_with_zeros(chunk);
let mut block = GenericArray::clone_from_slice(in_payload);
let cipher = Aes128::new(&key);
cipher.decrypt_block(&mut block);
if i > 0 {
decrypted_data.extend_from_slice(&block);
} else {
decrypted_data = block.to_vec();
}
}
decrypted_data
}