decrypt.rs 1.6 KB

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