Skip to content

Instantly share code, notes, and snippets.

@pridkett
Created July 5, 2012 15:13
Show Gist options
  • Save pridkett/3054267 to your computer and use it in GitHub Desktop.
Save pridkett/3054267 to your computer and use it in GitHub Desktop.
Calculate the hamming distance between messages from stdin and a given seed message. Used for a contest on Reddit.
import md5
base_message = "I want old gamecube games."
# get the hex digest as an integer
base_md5 = int(md5.md5(base_message).hexdigest(), 16)
starter_seed = "I would like to win your contest. Here's a word to shorten my md5 hamming distance: "
mindist = 128
for word in open("/usr/share/dict/words").readlines():
word = word.strip()
inp = starter_seed + word
# get the hex digest as an integer
inp_md5_hex = md5.md5(inp).hexdigest()
inp_md5 = int(inp_md5_hex, 16)
# calculate the xor of the binary representations
inp_xor = inp_md5 ^ base_md5
# sum up the hamming distance between the digests
hamming = sum([1 for x in bin(inp_xor) if x == '1'])
if hamming < mindist:
print starter_seed + word
print hamming
mindist = hamming
import sys
base_message = "I want old gamecube games."
# get the hex digest as an integer
base_md5 = int(md5.md5(base_message).hexdigest(), 16)
while 1:
# read input and strip it
inp = sys.stdin.read().strip()
# get the hex digest as an integer
inp_md5_hex = md5.md5(inp).hexdigest()
inp_md5 = int(inp_md5_hex, 16)
# calculate the xor of the binary representations
inp_xor = inp_md5 ^ base_md5
# sum up the hamming distance between the digests
hamming = sum([1 for x in bin(inp_xor) if x == '1'])
print inp_md5_hex
print hamming
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment