[kgm] refactor: convert to enum for dispatch

This commit is contained in:
鲁树人
2024-09-16 20:59:05 +01:00
parent e011f75d36
commit e45d09cf8e
5 changed files with 48 additions and 36 deletions

View File

@@ -1,7 +1,10 @@
pub mod header;
pub mod v2;
mod v3;
pub mod v3;
use crate::header::Header;
use crate::v2::DecipherV2;
use crate::v3::DecipherV3;
use thiserror::Error;
#[derive(Debug, Error)]
@@ -22,6 +25,37 @@ pub enum KugouError {
SelfTestFailed,
}
pub trait Decipher {
fn decrypt(&self, buffer: &mut [u8], offset: usize);
pub enum Decipher {
V2(DecipherV2),
V3(DecipherV3),
}
impl Decipher {
pub fn new(header: &Header) -> Result<Self, KugouError> {
let slot_key: &[u8] = match header.key_slot {
1 => b"l,/'",
slot => Err(KugouError::UnsupportedKeySlot(slot))?,
};
let decipher = match header.crypto_version {
2 => Decipher::V2(DecipherV2::new(header, slot_key)?),
3 => Decipher::V3(DecipherV3::new(header, slot_key)?),
version => Err(KugouError::UnsupportedCipherVersion(version))?,
};
let mut test_data = header.decrypt_test_data;
decipher.decrypt(&mut test_data, 0);
if test_data != header.get_challenge_data() {
Err(KugouError::SelfTestFailed)?;
}
Ok(decipher)
}
pub fn decrypt<T: AsMut<[u8]> + ?Sized>(&self, buffer: &mut T, offset: usize) {
match self {
Decipher::V2(decipher) => decipher.decrypt(buffer, offset),
Decipher::V3(decipher) => decipher.decrypt(buffer, offset),
}
}
}