use aes::{Aes128, Aes256};
use ctr::Ctr128BE;
use ctr::cipher::{KeyIvInit, StreamCipher};
use crate::error::{Error, Result};
pub struct EncrawDecryptor {
cipher: Cipher,
}
enum Cipher {
Aes128(Box<Ctr128BE<Aes128>>),
Aes256(Box<Ctr128BE<Aes256>>),
}
impl EncrawDecryptor {
pub fn from_hex_key(key_hex: &str) -> Result<Self> {
let key = hex::decode(key_hex.trim())
.map_err(|e| Error::InvalidBitrate(format!("encraw key is not valid hex: {e}")))?;
let iv = [0u8; 16];
let cipher = match key.len() {
16 => Cipher::Aes128(Box::new(Ctr128BE::<Aes128>::new(
key.as_slice().into(),
&iv.into(),
))),
32 => Cipher::Aes256(Box::new(Ctr128BE::<Aes256>::new(
key.as_slice().into(),
&iv.into(),
))),
other => {
return Err(Error::InvalidBitrate(format!(
"encraw key must be 16 or 32 bytes, got {other}"
)));
},
};
Ok(Self { cipher })
}
pub fn apply(&mut self, chunk: &mut [u8]) {
match &mut self.cipher {
Cipher::Aes128(c) => c.apply_keystream(chunk),
Cipher::Aes256(c) => c.apply_keystream(chunk),
}
}
}
pub fn decrypt_encraw(data: &[u8], key_hex: &str) -> Result<Vec<u8>> {
let mut out = data.to_vec();
EncrawDecryptor::from_hex_key(key_hex)?.apply(&mut out);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
const KEY_128: &str = "000102030405060708090a0b0c0d0e0f";
const KEY_256: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
#[test]
fn decryption_is_its_own_inverse() {
for key in [KEY_128, KEY_256] {
let plain = b"fLaC\x00\x00\x00\x22 some audio payload".to_vec();
let encrypted = decrypt_encraw(&plain, key).unwrap();
assert_ne!(encrypted, plain, "keystream must actually alter the bytes");
assert_eq!(decrypt_encraw(&encrypted, key).unwrap(), plain);
}
}
#[test]
fn streaming_in_chunks_matches_one_shot() {
let plain: Vec<u8> = (0..=255u8).cycle().take(4096 + 37).collect();
let one_shot = decrypt_encraw(&plain, KEY_256).unwrap();
let mut streamed = Vec::new();
let mut dec = EncrawDecryptor::from_hex_key(KEY_256).unwrap();
for chunk in plain.chunks(7) {
let mut buf = chunk.to_vec();
dec.apply(&mut buf);
streamed.extend_from_slice(&buf);
}
assert_eq!(streamed, one_shot);
}
#[test]
fn key_length_selects_the_cipher() {
let plain = b"same input, different key length".to_vec();
let with_128 = decrypt_encraw(&plain, KEY_128).unwrap();
let with_256 = decrypt_encraw(&plain, KEY_256).unwrap();
assert_ne!(with_128, with_256);
}
#[test]
fn malformed_keys_are_rejected() {
assert!(decrypt_encraw(b"x", "not hex").is_err());
assert!(
decrypt_encraw(b"x", "00112233").is_err(),
"4 bytes is neither 16 nor 32"
);
assert!(decrypt_encraw(b"x", "").is_err());
assert!(decrypt_encraw(b"x", &"ab".repeat(24)).is_err());
}
#[test]
fn keys_tolerate_surrounding_whitespace() {
assert!(EncrawDecryptor::from_hex_key(&format!(" {KEY_128}\n")).is_ok());
}
#[test]
fn empty_input_stays_empty() {
assert!(decrypt_encraw(&[], KEY_128).unwrap().is_empty());
}
}