Midea/src/security.rs
2023-09-22 12:34:35 +02:00

61 lines
1.5 KiB
Rust

use aes::{
cipher::{generic_array::GenericArray, BlockDecrypt, KeyInit},
Aes128,
};
use anyhow::Result;
use rand::{self, RngCore};
use crate::hex;
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MsgType {
HANDSHAKE_REQUEST = 0x0,
ANDSHAKE_RESPONSE = 0x1,
ENCRYPTED_RESPONSE = 0x3,
ENCRYPTED_REQUEST = 0x6,
}
pub struct Security;
impl Security {
pub fn decrypt(data: &mut [u8]) -> &[u8] {
const N: u128 = 141661095494369103254425781617665632877;
const KEY: [u8; 16] = N.to_be_bytes();
let array = GenericArray::from(KEY);
let cipher = Aes128::new(&array);
for chunk in data.chunks_mut(16) {
let mut block = GenericArray::from_mut_slice(chunk);
cipher.decrypt_block(&mut block);
}
data
}
pub fn encode_8370(msg_type: MsgType) -> Result<String> {
let mut header = hex("83,70")?;
let mut data: Vec<u8> = Vec::new();
let mut size = data.len();
let mut padding = 0;
if msg_type == MsgType::ENCRYPTED_RESPONSE || msg_type == MsgType::ENCRYPTED_REQUEST {
if (size + 2) % 16 != 0 {
padding = 16 - ((size + 2) & 0xf);
size += padding + 32;
data.extend({
let mut d = vec![0; padding];
rand::thread_rng().fill_bytes(&mut d);
d
});
}
}
todo!()
}
}