-
Notifications
You must be signed in to change notification settings - Fork 0
/
checksum.py
67 lines (51 loc) · 1.52 KB
/
checksum.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
"""
4-byte checksum for message
------------------------------------------------------------
It shows how weak checksum is thus it's incapable of being \\
a cryptographic hash function
e.g.
"IOU100.99BOB"
and
"IOU900.19BOB"
both have the checksum: ['0xb2', '0xc1', '0xd2', '0xac']
Here we get a Hash Collision!
------------------------------------------------------------
"""
__author__ = "LYK-love"
COL_NUM = 4
def list2matrix(input_list, col_num):
"""
convert list to a matrix with given col_num,
NBL this means the length of the input_list is just multiples of col_num
"""
mat = []
while input_list != []:
mat.append(input_list[:col_num])
input_list = input_list[col_num:]
return mat
def checksum(mat, row_num, col_num):
"""
calculate the check sum of the given row_num * col_num matrix
"""
res = []
# 从最后一列开始加
for col in range(col_num - 1, -1, -1):
sum = 0
for row in range(0, row_num):
sum += mat[row][col]
res.append(sum)
# 结果反转
res.reverse()
return res
text = input("input = ") or "IOU100.99BOB"
if len(text) % COL_NUM is not 0:
raise Exception(
"the length of input text must be multiples of col_num, which is {}".format(
COL_NUM
)
)
ascii_list = list(map(ord, list(text)))
mat = list2matrix(ascii_list, COL_NUM)
check_sum_list = checksum(mat, row_num=len(mat), col_num=COL_NUM)
hex_check_sum_list = list(map(hex, check_sum_list))
print(hex_check_sum_list)