Skip to content

Commit e850d8d

Browse files
Merge pull request geekcomputers#426 from nautiyaldeepak/master
sha1 hashing script
2 parents a5089ca + d51b75e commit e850d8d

File tree

1 file changed

+122
-0
lines changed

1 file changed

+122
-0
lines changed

sha1.py

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import argparse
2+
import struct
3+
import hashlib #hashlib is only used inside the Test class
4+
import unittest
5+
6+
7+
class SHA1Hash:
8+
"""
9+
Class to contain the entire pipeline for SHA1 Hashing Algorithm
10+
"""
11+
def __init__(self, data):
12+
"""
13+
Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal
14+
numbers corresponding to (1732584193, 4023233417, 2562383102, 271733878, 3285377520)
15+
respectively. We will start with this as a message digest. 0x is how you write
16+
Hexadecimal numbers in Python
17+
"""
18+
self.data = data
19+
self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
20+
21+
@staticmethod
22+
def rotate(n, b):
23+
"""
24+
Static method to be used inside other methods. Left rotates n by b.
25+
"""
26+
return ((n << b) | (n >> (32 - b))) & 0xffffffff
27+
28+
def padding(self):
29+
"""
30+
Pads the input message with zeros so that padded_data has 64 bytes or 512 bits
31+
"""
32+
padding = b'\x80' + b'\x00'*(63 - (len(self.data) + 8) % 64)
33+
padded_data = self.data + padding + struct.pack('>Q', 8 * len(self.data))
34+
return padded_data
35+
36+
def split_blocks(self):
37+
"""
38+
Returns a list of bytestrings each of length 64
39+
"""
40+
return [self.padded_data[i:i+64] for i in range(0, len(self.padded_data), 64)]
41+
42+
# @staticmethod
43+
def expand_block(self, block):
44+
"""
45+
Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a
46+
list of 80 integers pafter some bit operations
47+
"""
48+
w = list(struct.unpack('>16L', block)) + [0] * 64
49+
for i in range(16, 80):
50+
w[i] = self.rotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)
51+
return w
52+
53+
def final_hash(self):
54+
"""
55+
Calls all the other methods to process the input. Pads the data, then splits into
56+
blocks and then does a series of operations for each block (including expansion).
57+
For each block, the variable h that was initialized is copied to a,b,c,d,e
58+
and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are
59+
processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1] and so on.
60+
This h becomes our final hash which is returned.
61+
"""
62+
self.padded_data = self.padding()
63+
self.blocks = self.split_blocks()
64+
for block in self.blocks:
65+
expanded_block = self.expand_block(block)
66+
a, b, c, d, e = self.h
67+
for i in range(0, 80):
68+
if 0 <= i < 20:
69+
f = (b & c) | ((~b) & d)
70+
k = 0x5A827999
71+
elif 20 <= i < 40:
72+
f = b ^ c ^ d
73+
k = 0x6ED9EBA1
74+
elif 40 <= i < 60:
75+
f = (b & c) | (b & d) | (c & d)
76+
k = 0x8F1BBCDC
77+
elif 60 <= i < 80:
78+
f = b ^ c ^ d
79+
k = 0xCA62C1D6
80+
a, b, c, d, e = self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xffffffff,\
81+
a, self.rotate(b, 30), c, d
82+
self.h = self.h[0] + a & 0xffffffff,\
83+
self.h[1] + b & 0xffffffff,\
84+
self.h[2] + c & 0xffffffff,\
85+
self.h[3] + d & 0xffffffff,\
86+
self.h[4] + e & 0xffffffff
87+
return '%08x%08x%08x%08x%08x' %tuple(self.h)
88+
89+
90+
class SHA1HashTest(unittest.TestCase):
91+
"""
92+
Test class for the SHA1Hash class. Inherits the TestCase class from unittest
93+
"""
94+
def testMatchHashes(self):
95+
msg = bytes('Test String', 'utf-8')
96+
self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest())
97+
98+
99+
def main():
100+
"""
101+
Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash.
102+
unittest.main() has been commented because we probably dont want to run
103+
the test each time.
104+
"""
105+
# unittest.main()
106+
parser = argparse.ArgumentParser(description='Process some strings or files')
107+
parser.add_argument('--string', dest='input_string',
108+
default='Hello World!! Welcome to Cryptography',
109+
help='Hash the string')
110+
parser.add_argument('--file', dest='input_file', help='Hash contents of a file')
111+
args = parser.parse_args()
112+
input_string = args.input_string
113+
#In any case hash input should be a bytestring
114+
if args.input_file:
115+
hash_input = open(args.input_file, 'rb').read()
116+
else:
117+
hash_input = bytes(input_string, 'utf-8')
118+
print(SHA1Hash(hash_input).final_hash())
119+
120+
121+
if __name__ == '__main__':
122+
main()

0 commit comments

Comments
 (0)