Skip to content

Instantly share code, notes, and snippets.

@opieters
Last active April 23, 2016 18:52
Show Gist options
  • Save opieters/67fe520ba70faec8d23b65fbaa28fe09 to your computer and use it in GitHub Desktop.
Save opieters/67fe520ba70faec8d23b65fbaa28fe09 to your computer and use it in GitHub Desktop.
from Crypto.Hash import SHA256
import struct, random, yaml, time
# hash to match
h = SHA256.new(b"123456")
ref = int(h.hexdigest(),16)
# config
treshhold, timeout = 20, 120 # require AT LEAST 20 matching initial bits!
# run till keyboard interrupt and then save file
while True:
matches, start_value, max_match, max_value = [], 0, 0, 0
end_time = time.time() + timeout
# generate a random start value
for i in range(32):
start_value = (start_value << 8) + random.randint(0, 2^8-1)
try:
value = start_value
while time.time() < end_time:
# update hash
h = SHA256.new(str.encode("%d" % value))
# extract infomation into int
new = int(h.hexdigest(), 16)
# compare bits
v, i = format(ref ^ new, '0256b'), 0
while i < 256 and int(v[i], 2) == 0:
i += 1
# write to file if enough similarity
if i >= treshhold:
matches.append([value, i])
print("Match of %03d bits" % i)
if max_match < i:
print("NEW MAX MATCH FOUND! %d" % i)
max_match = i
max_value = value
# update value
value += 1
finally:
print("Stopped at: %d" % value)
with open("hash-file-%f.yml" % time.time(), 'w') as f:
data = {"matches": matches, "start": start_value, "end": value}
f.write(yaml.dump(data))
print("Max (%d): %d" % (max_match, max_value))
@opieters
Copy link
Author

opieters commented Apr 23, 2016

Assignment for Information Security course: try to match as many first bits as possible to a certain reference SHA-256 hash value. This small script executes a simple brute-force matching by means of the PyCryptodome suite.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment