decrypt.rs 1.7 KB

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