did part 4
This commit is contained in:
parent
ec14efb417
commit
d97955909f
34
part4/4a.py
Normal file
34
part4/4a.py
Normal file
@ -0,0 +1,34 @@
|
||||
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]
|
||||
|
||||
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:
|
||||
print(f'Message 1 "{m}" and message 2 "{messages[hashes.index(hm)]}" have the same hash {hm}.')
|
||||
print(f'It took {i} iterations to find a collision.')
|
||||
break
|
||||
else:
|
||||
hashes.append(hm)
|
||||
messages.append(m)
|
||||
|
||||
i += 1
|
||||
|
||||
37
part4/4b.py
Normal file
37
part4/4b.py
Normal file
@ -0,0 +1,37 @@
|
||||
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)}')
|
||||
Loading…
x
Reference in New Issue
Block a user