From d97955909f5ea437afaab0eade5a668636f00b61 Mon Sep 17 00:00:00 2001 From: JISAUAY Date: Tue, 28 Oct 2025 13:23:54 -0500 Subject: [PATCH] did part 4 --- part4/4a.py | 34 ++++++++++++++++++++++++++++++++++ part4/4b.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 part4/4a.py create mode 100644 part4/4b.py diff --git a/part4/4a.py b/part4/4a.py new file mode 100644 index 0000000..2e996b9 --- /dev/null +++ b/part4/4a.py @@ -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 + diff --git a/part4/4b.py b/part4/4b.py new file mode 100644 index 0000000..f8ff6d2 --- /dev/null +++ b/part4/4b.py @@ -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)}')