diff signature_gen.py @ 49:1bd17c2e5517 default tip

video.py must sign video urls for serve-files.js to serve them
author drewp@bigasterisk.com
date Fri, 06 Dec 2024 17:13:51 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/signature_gen.py	Fri Dec 06 17:13:51 2024 -0800
@@ -0,0 +1,26 @@
+import base64
+import json
+import logging
+from pathlib import Path
+import time
+
+from Crypto.Cipher import AES
+from Crypto.Random import get_random_bytes
+from Crypto.Util.Padding import pad
+
+log = logging.getLogger()
+
+
+SIGNATURE_KEY = Path('/secret/signature_key').read_bytes()
+
+def _encrypt_data(data: bytes, key: bytes) -> str:
+    iv = get_random_bytes(12)
+    cipher = AES.new(key, AES.MODE_GCM, iv)
+    ciphertext, tag = cipher.encrypt_and_digest(pad(data, AES.block_size))
+    return base64.b64encode(iv + ciphertext + tag).decode('utf-8')
+
+
+def makePlaybackSig(user: str, webDataPath: str, lifeSeconds=3600) -> str:
+    msg = [user, webDataPath, int(time.time() + lifeSeconds)]
+    return _encrypt_data(
+        json.dumps(msg).encode('utf-8'), SIGNATURE_KEY)