Skip to content

Instantly share code, notes, and snippets.

@sh4dowb
Created April 11, 2025 02:06
Show Gist options
  • Save sh4dowb/9337d849ab13b76c8f2e2b62d327e498 to your computer and use it in GitHub Desktop.
Save sh4dowb/9337d849ab13b76c8f2e2b62d327e498 to your computer and use it in GitHub Desktop.
verify chrome extension files with verified_contents.json in python
import json
import base64
import hashlib
import zipfile
import sys
BRANCH_FACTOR = 128
BLOCK_SIZE = 4096
DIGEST_SIZE = 32
def sha256(data):
return hashlib.sha256(data).digest()
def tree_hash_root(data: bytes, block_size: int = BLOCK_SIZE) -> bytes:
leaf_hashes = [
sha256(data[i:i + block_size])
for i in range(0, len(data), block_size)
]
if not leaf_hashes:
return sha256(b'')
current = leaf_hashes
while len(current) > 1:
next_level = []
for i in range(0, len(current), BRANCH_FACTOR):
group = current[i:i + BRANCH_FACTOR]
hasher = hashlib.sha256()
for h in group:
hasher.update(h)
next_level.append(hasher.digest())
current = next_level
return current[0]
zip_path = sys.argv[1]
metadata_path = "_metadata/verified_contents.json"
matched, failed = 0, 0
with zipfile.ZipFile(zip_path, "r") as archive:
with open(metadata_path, "r") as meta_file:
metadata = json.load(meta_file)
payload_b64 = metadata[0]['signed_content']['payload'] + '=='
payload = json.loads(base64.b64decode(payload_b64))
for file_info in payload['content_hashes'][0]['files']:
file_path = file_info['path']
expected_hash_b64 = file_info['root_hash']
expected_hash_b64 += '_' * (-len(expected_hash_b64) % 4)
expected_hash = base64.urlsafe_b64decode(expected_hash_b64)[:DIGEST_SIZE]
with archive.open(file_path) as f:
content = f.read()
actual_hash = tree_hash_root(content, block_size=BLOCK_SIZE)
if actual_hash != expected_hash:
failed += 1
print("fail", len(content), file_path, expected_hash.hex(), actual_hash.hex())
else:
matched += 1
# print("match", len(content), file_path)
print("failed files:",failed)
print("matched files:",matched)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment