Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. import sys, os
  2.  
  3. import shutil
  4. from Crypto.Cipher import AES
  5.  
  6. def parse_m3u8_file(m3u8_file):
  7. with open(m3u8_file, 'rb') as fp:
  8. current_line = fp.readline().rstrip('\n')
  9. while (current_line):
  10. if current_line.startswith('#EXT-X-KEY'):
  11. comps = current_line.split(',')
  12. URI = comps[1][5:-1]
  13. IV = comps[2][5:].rstrip('\n')
  14. with open(URI, 'rb') as urifp:
  15. KEY = urifp.readline().rstrip('\n')
  16. fp.readline()
  17. ts_file = fp.readline().rstrip('\n')
  18. yield (IV, KEY, ts_file)
  19. current_line = fp.readline()
  20.  
  21. def decrypt(ciphertext, key, iv):
  22. cipher = AES.new(key, AES.MODE_CBC, iv)
  23. plaintext = cipher.decrypt(ciphertext[AES.block_size:])
  24. return plaintext.rstrip(b"\0")
  25.  
  26. def decrypt_aes_128_ts_file(iv, key, ts_file):
  27. print(iv, key, ts_file)
  28. out = ts_file[:-2]+'.tsd'
  29. if os.path.exists(out):
  30. return out
  31. with open(ts_file, 'rb') as fo:
  32. ciphertext = fo.read()
  33. dec = decrypt(ciphertext, key, iv.decode('hex'))
  34. with open(out, 'wb') as fo:
  35. fo.write(dec)
  36. return out
  37.  
  38. if __name__ == '__main__':
  39. if len(sys.argv) != 2:
  40. print('Usage: python %s m3u8_file' % sys.argv[0])
  41. sys.exit(1)
  42.  
  43. m3u8 = sys.argv[1]
  44. if not os.path.exists(m3u8) or not m3u8.endswith('.m3u8'):
  45. print('Input file should be a m3u8 file.')
  46. sys.exit(1)
  47.  
  48. tsd_files = []
  49. for (iv, key, ts_file) in parse_m3u8_file(m3u8):
  50. tsd_files.append(decrypt_aes_128_ts_file(iv, key, ts_file))
  51.  
  52. with open(m3u8[:-4]+'ts', 'wb') as merged:
  53. for ts_file in tsd_files:
  54. with open(ts_file, 'rb') as mergefile:
  55. shutil.copyfileobj(mergefile, merged)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement