BenKrueger

decode_hex_image.py

Dec 3rd, 2025
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | Cybersecurity | 0 0
  1. #!/usr/bin/env python3
  2. from PIL import Image, UnidentifiedImageError
  3. import sys
  4.  
  5. BLOCK_SIZE = 6
  6.  
  7.  
  8. def extract_cipher_bytes_from_png(path):
  9.     img = Image.open(path)
  10.     w, h = img.size
  11.     pixels = img.load()
  12.  
  13.     data = bytearray()
  14.     for y in range(h):
  15.         for x in range(w):
  16.             r, g, b = pixels[x, y]
  17.             data.append(b)
  18.     return data
  19.  
  20.  
  21. def decrypt_chain(cipher: bytes) -> bytes:
  22.     # Nur volle Blöcke verwenden (Rest abschneiden)
  23.     usable_len = len(cipher) - (len(cipher) % BLOCK_SIZE)
  24.     cipher = cipher[:usable_len]
  25.  
  26.     blocks = [cipher[i:i + BLOCK_SIZE] for i in range(0, len(cipher), BLOCK_SIZE)]
  27.     if len(blocks) < 2:
  28.         return b""
  29.  
  30.     pt = bytearray()
  31.  
  32.     # Erster Block: unbekannt (C0 XOR K) -> Platzhalter
  33.     pt += b"??????"
  34.  
  35.     # Alle folgenden: Pi = Ci XOR C(i-1)
  36.     for i in range(1, len(blocks)):
  37.         c_prev = blocks[i - 1]
  38.         c_cur = blocks[i]
  39.         pt_block = bytes(c_cur[j] ^ c_prev[j] for j in range(BLOCK_SIZE))
  40.         pt += pt_block
  41.  
  42.     return bytes(pt)
  43.  
  44.  
  45. def main():
  46.     if len(sys.argv) < 2:
  47.         print("usage: decode_hex_image.py <input_file> [output.bin]")
  48.         sys.exit(1)
  49.  
  50.     in_file = sys.argv[1]
  51.     out_file = sys.argv[2] if len(sys.argv) > 2 else None
  52.  
  53.     # 1) Versuchen als PNG
  54.     try:
  55.         cipher = extract_cipher_bytes_from_png(in_file)
  56.         print(f"[+] Interpreted '{in_file}' as PNG (blue channel).")
  57.     except (UnidentifiedImageError, OSError):
  58.         # 2) Fallback: rohe Bytes
  59.         print(f"[!] '{in_file}' is not a valid PNG, treating it as raw cipher bytes.")
  60.         with open(in_file, "rb") as f:
  61.             cipher = f.read()
  62.  
  63.     print(f"[i] Cipher length: {len(cipher)} bytes (len % {BLOCK_SIZE} = {len(cipher) % BLOCK_SIZE})")
  64.  
  65.     plain = decrypt_chain(cipher)
  66.  
  67.     if out_file:
  68.         with open(out_file, "wb") as f:
  69.             f.write(plain)
  70.         print(f"[+] Wrote decrypted data to: {out_file}")
  71.     else:
  72.         sys.stdout.buffer.write(plain)
  73.  
  74.  
  75. if __name__ == "__main__":
  76.     main()
  77.  
Advertisement
Add Comment
Please, Sign In to add comment