# This code is quite straightforward, one exception being the inclusion of a random string from the receiving party, Bob, in this case, # in the hash. This gives Bob assurance that Alice didn't precompute two hashes, "heads random string" and "tails another random string", # with the same hash value. This is really paranoia in the extreme as modern hashes are collision-free to a very high degree of probability. # The following Python program is an implementation of coin-flipping using a cryptographic hash: #!/usr/local/bin/python3 from hashlib import sha256 from random import random, randrange MAX_S, CHARS, FIRST_ASCII = 55, 26, 97 alice_s = '' for i in range(MAX_S): alice_s += chr(randrange(CHARS) + FIRST_ASCII) print("\nAlice's string is", alice_s) bob_s = '' for i in range(MAX_S): bob_s += chr(randrange(CHARS) + FIRST_ASCII) print("\nBob's string is", bob_s) if random() > 0.5: outcome = 'heads' else: outcome = 'tails' s_to_hash = outcome + ' ' + alice_s + ' ' + bob_s hash_out = sha256(s_to_hash.encode('utf-8')).hexdigest() print("""\ Alice chooses {0:s} and sends Bob the hash of {0:s} + ' ' + her string + ' ' + Bob's string = {1:s} """.format(outcome, hash_out)) if random() > 0.5: bob_guess = 'heads' else: bob_guess = 'tails' print('Bob chooses', bob_guess) if bob_guess == outcome: print('\nBob wins') else: print("""\ Alice wins Alice sends Bob her string so that he can do the hash and confirm her choice. """) # End of Code # Test Ouput 1 (Alice wins): # Alice's string is bmqujztahsqwmwjeckcfrhqwnfcwvjrgrexjeobbbqmbenffdfqbxrn # Bob's string is zrcvoxpcfslphvjqacyptewditwjqixkejdlkvuejrisrtnujattshy # Alice chooses tails and sends Bob the hash of tails + her string + ' ' + Bob's string = 28b287547f6f720dd239b0c322168f2a489481cead48fd40363be9edf4383fda # Bob chooses heads # Alice wins # Alice sends Bob her string so that he can do the hash and confirm her choice. # Test Output 2 (Bob wins): # Alice's string is lpemcvcatlmbytzhkvmxukclwbzkelxpsusimakwuoxjdlhntneusux # Bob's string is zftwyecehvncmsnqclqutugpofepvtjlfiuovyjcmzvayihbdkaabae # Alice chooses tails and sends Bob the hash of tails + her string + ' ' + Bob's string = 6337c3688ffc8fc77eebae69d4c420bb0cae633767d9faed7eac34a42cea1d9b # Bob chooses tails # Bob wins