-
Notifications
You must be signed in to change notification settings - Fork 0
/
dictionary.py
68 lines (51 loc) · 2.66 KB
/
dictionary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Program to find the time taken by SHA-1 algorithm for collisions for different number of bits
# importing required libraries
import random
import hashlib
import time
import xlwt
from xlwt import Workbook
from xlrd import open_workbook
from xlutils.copy import copy
# Open excel sheet for storing data
rb = open_workbook("data-dict.xls")
wb = copy(rb)
sheet1 = wb.get_sheet(0)
for ch in range(1, 14): # ch denotes the number of characters or hexadecimal digits to be compared
sheet1.write(4 * (ch) - 3, 0, "Number of characters = " + str(ch))
sheet1.write(4 * (ch) - 2, 0, "POSITIONS")
sheet1.write(4 * (ch) - 1, 0, "TIME") # printing the required row headings
for i in range(10):
randlist = random.sample(range(40), ch) # generating a list of ch random positions
print(randlist)
total_time = 0
count = 100 # count = number of trials for each set of positions
for j in range(count):
collission = {} # initialising the dictionary
start_time = time.time()
while 1:
input = random.randint(1000, 100000000000000000000000000) # random number generator
# hashlib generates the hash value and stores the digest in result
# in this program, the algorithm used is SHA-1
# the algorithm can be changed by replacing 'sha1' in 'hashlib.sha1' with 'md5', 'sha256' or 'sha512'
result = hashlib.sha1(str(input).encode()).hexdigest()
# Generating a string by concatenating characters from the randomly chosen positions
hashstr = ""
for k in randlist:
hashstr = hashstr + str(result)[k]
if (hashstr in collission) == True: # checks if the string had been generated earlier
print(input) # printing collision details to the output console
print(collission[hashstr])
print("Digit " + str(ch) + " collision " + str(j + 1) + " in " + str(i + 1))
print(time.time() - start_time)
break
else:
collission.update({hashstr: input}) # appending the new string to the dictionary
final_time = (time.time() - start_time) # calculating the time taken for collision
total_time = total_time + final_time
total_time = total_time / count
print(total_time)
# code for writing the data values into the excel sheet
sheet1.write(4 * (ch) - 2, i + 1, str(randlist))
sheet1.write(4 * (ch) - 1, i + 1, total_time)
wb.save('data-dict.xls')