audio_decrypt.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use crypto::aes;
  2. use crypto::symmetriccipher::SynchronousStreamCipher;
  3. use num::{BigUint, FromPrimitive};
  4. use std::io;
  5. use std::ops::Add;
  6. use audio_key::AudioKey;
  7. const AUDIO_AESIV: &'static [u8] = &[0x72, 0xe0, 0x67, 0xfb, 0xdd, 0xcb, 0xcf, 0x77, 0xeb, 0xe8,
  8. 0xbc, 0x64, 0x3f, 0x63, 0x0d, 0x93];
  9. pub struct AudioDecrypt<T: io::Read> {
  10. cipher: Box<SynchronousStreamCipher + 'static>,
  11. key: AudioKey,
  12. reader: T,
  13. }
  14. impl<T: io::Read> AudioDecrypt<T> {
  15. pub fn new(key: AudioKey, reader: T) -> AudioDecrypt<T> {
  16. let cipher = aes::ctr(aes::KeySize::KeySize128, &key, AUDIO_AESIV);
  17. AudioDecrypt {
  18. cipher: cipher,
  19. key: key,
  20. reader: reader,
  21. }
  22. }
  23. }
  24. impl<T: io::Read> io::Read for AudioDecrypt<T> {
  25. fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
  26. let mut buffer = vec![0u8; output.len()];
  27. let len = try!(self.reader.read(&mut buffer));
  28. self.cipher.process(&buffer[..len], &mut output[..len]);
  29. Ok(len)
  30. }
  31. }
  32. impl<T: io::Read + io::Seek> io::Seek for AudioDecrypt<T> {
  33. fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
  34. let newpos = try!(self.reader.seek(pos));
  35. let skip = newpos % 16;
  36. let iv = BigUint::from_bytes_be(AUDIO_AESIV)
  37. .add(BigUint::from_u64(newpos / 16).unwrap())
  38. .to_bytes_be();
  39. self.cipher = aes::ctr(aes::KeySize::KeySize128, &self.key, &iv);
  40. let buf = vec![0u8; skip as usize];
  41. let mut buf2 = vec![0u8; skip as usize];
  42. self.cipher.process(&buf, &mut buf2);
  43. Ok(newpos as u64)
  44. }
  45. }