Skip to content

Commit

Permalink
Fix decryption upadding 2 (#13)
Browse files Browse the repository at this point in the history
* fix unpad logic in videio segment decryption

* use cryptography instead of pycryptodome

* update dependencies
  • Loading branch information
sakkyoi authored Sep 15, 2024
1 parent c22df7a commit 1e15199
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
12 changes: 6 additions & 6 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
click==8.1.7
requests==2.32.3
m3u8==6.0.0
pycryptodome==3.19.1
inquirer==3.3.0
cryptography==43.0.1
inquirer==3.4.0
tinydb==4.8.0
pathvalidate==3.2.0
typer[all]==0.12.3
rich==13.7.1
setuptools==72.1.0
pathvalidate==3.2.1
typer[all]==0.12.5
rich==13.8.1
setuptools==74.1.2
pylibimport==1.9.2
26 changes: 21 additions & 5 deletions util/m3u8_downloader.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import requests
import m3u8
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC as RFC8216MediaSegmentEncryptMode
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.padding import PKCS7
import time
import inquirer
from pathlib import Path
Expand Down Expand Up @@ -54,9 +57,15 @@ def __init__(self, api_client: NCP, progress_manager: ProgressManager, session_i
# init manager
self.m3u8_manager = M3U8Manager(f'{self.output}.ts', resume=self.resume)

# data load from session
self.video_index = None
self.target_video = None
self.key = None

# decrypt settings
self.algorithm = AES # Decrypt algorithm
self.mode = RFC8216MediaSegmentEncryptMode # Decrypt mode
self.unpadder = PKCS7(128)
self.key = None # Decrypt key

# init task progress
self.task = self.progress_manager.add_task('Start downloading', total=None)
Expand Down Expand Up @@ -139,9 +148,16 @@ def __decrypt(self, content: bytes, media_sequence):
please refer to RFC 8216, Section 5.2:
https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-5.2
"""
cipher = AES.new(self.key, AES.MODE_CBC, media_sequence.to_bytes(16, 'big'))
iv = media_sequence.to_bytes(16, 'big')
cipher = Cipher(self.algorithm(self.key), self.mode(iv), backend=default_backend())

decryptor = cipher.decryptor()
decrypted = decryptor.update(content) + decryptor.finalize()

unpadder = self.unpadder.unpadder()
unpadded = unpadder.update(decrypted) + unpadder.finalize()

return unpad(cipher.decrypt(content), AES.block_size, style='pkcs7')
return unpadded

def __init_manager(self) -> None:
"""Initialize M3U8Manager"""
Expand Down

0 comments on commit 1e15199

Please sign in to comment.