import hashlib
import io
import time
import numpy as np
from PIL import Image
import csv
import random
# -------------------------------------------------------------
# 1. LOAD IMAGE AND RETURN RAW BUFFER
# -------------------------------------------------------------
def get_image_buffer(path):
img = Image.open(path).convert("RGB")
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
# -------------------------------------------------------------
# 2. 64-BIT ONE-WAY HASH
# -------------------------------------------------------------
def hash64(data):
full = hashlib.sha256(data).digest()
return full[:8] # 64 bits
# -------------------------------------------------------------
# 3. HASH DISTANCE (Hamming)
# -------------------------------------------------------------
def hash_distance(h1, h2):
return sum(bin(a ^ b).count("1") for a, b in zip(h1, h2))
# -------------------------------------------------------------
# 4. TIMESTAMP + MUTATION ENGINE
# -------------------------------------------------------------
def mutate_buffer(base_bytes, timestamp):
candidate = bytearray(base_bytes)
# timestamp XOR
ts_bytes = int(timestamp).to_bytes(8, "little")
for i in range(min(len(candidate), len(ts_bytes))):
candidate[i] ^= ts_bytes[i]
# random micro-mutation
idx = random.randint(0, len(candidate)-1)
candidate[idx] ^= random.randint(0, 255)
return bytes(candidate)
# -------------------------------------------------------------
# 5. REVERSE ATTEMPT LOOP
# -------------------------------------------------------------
def reverse_attempt(target_hash, base_bytes, iterations=50000):
results = []
best_candidate = None
best_distance = 999
for i in range(iterations):
ts = time.time_ns()
candidate = mutate_buffer(base_bytes, ts)
h = hash64(candidate)
dist = hash_distance(h, target_hash)
if dist < best_distance:
best_distance = dist
best_candidate = candidate
print(f"New best distance: {dist}")
match = (h == target_hash)
results.append((ts, h.hex(), dist, match))
if match:
print("Exact pre-image found!")
return candidate, results
return best_candidate, results
# -------------------------------------------------------------
# 6. RUN PIPELINE
# -------------------------------------------------------------
buf = get_image_buffer("input.png")
target_hash = hash64(buf)
print("Target 64-bit hash:", target_hash.hex())
candidate, results = reverse_attempt(target_hash, buf)
# -------------------------------------------------------------
# 7. LOG RESULTS
# -------------------------------------------------------------
with open("reverse_attempt_log.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["timestamp_ns", "hash", "distance", "match"])
writer.writerows(results)
print("Pipeline complete.")






No comments:
Post a Comment