38 lines
710 B
Python
38 lines
710 B
Python
import string
|
|
import random
|
|
import hashlib
|
|
|
|
letters = string.ascii_lowercase + string.ascii_uppercase
|
|
|
|
# 4a
|
|
|
|
def H(m: str) -> str:
|
|
return hashlib.sha256(m.encode()).hexdigest()[:2]
|
|
|
|
|
|
counts = []
|
|
for n in range(20):
|
|
i = 0
|
|
hashes = []
|
|
messages = []
|
|
while True:
|
|
|
|
n_char = random.randint(1, 1000)
|
|
m = ''.join([random.choice(letters) for n in range(n_char)])
|
|
hm = H(m)
|
|
|
|
# print(i)
|
|
# print(m)
|
|
# print(hm)
|
|
|
|
if hm in hashes:
|
|
counts.append(i)
|
|
break
|
|
else:
|
|
hashes.append(hm)
|
|
messages.append(m)
|
|
|
|
i += 1
|
|
|
|
print(f'Average number of trials for a collision: {sum(counts)/len(counts)}')
|