Class to contain the entire pipeline for SHA1 Hashing Algorithm
| 5 | |
| 6 | |
| 7 | class SHA1Hash: |
| 8 | """ |
| 9 | Class to contain the entire pipeline for SHA1 Hashing Algorithm |
| 10 | """ |
| 11 | |
| 12 | def __init__(self, data): |
| 13 | """ |
| 14 | Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal |
| 15 | numbers corresponding to (1732584193, 4023233417, 2562383102, 271733878, 3285377520) |
| 16 | respectively. We will start with this as a message digest. 0x is how you write |
| 17 | Hexadecimal numbers in Python |
| 18 | """ |
| 19 | self.data = data |
| 20 | self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] |
| 21 | |
| 22 | @staticmethod |
| 23 | def rotate(n, b): |
| 24 | """ |
| 25 | Static method to be used inside other methods. Left rotates n by b. |
| 26 | """ |
| 27 | return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF |
| 28 | |
| 29 | def padding(self): |
| 30 | """ |
| 31 | Pads the input message with zeros so that padded_data has 64 bytes or 512 bits |
| 32 | """ |
| 33 | padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) |
| 34 | padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) |
| 35 | return padded_data |
| 36 | |
| 37 | def split_blocks(self): |
| 38 | """ |
| 39 | Returns a list of bytestrings each of length 64 |
| 40 | """ |
| 41 | return [ |
| 42 | self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64) |
| 43 | ] |
| 44 | |
| 45 | # @staticmethod |
| 46 | def expand_block(self, block): |
| 47 | """ |
| 48 | Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a |
| 49 | list of 80 integers pafter some bit operations |
| 50 | """ |
| 51 | w = list(struct.unpack(">16L", block)) + [0] * 64 |
| 52 | for i in range(16, 80): |
| 53 | w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1) |
| 54 | return w |
| 55 | |
| 56 | def final_hash(self): |
| 57 | """ |
| 58 | Calls all the other methods to process the input. Pads the data, then splits into |
| 59 | blocks and then does a series of operations for each block (including expansion). |
| 60 | For each block, the variable h that was initialized is copied to a,b,c,d,e |
| 61 | and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are |
| 62 | processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1] and so on. |
| 63 | This h becomes our final hash which is returned. |
| 64 | """ |
no outgoing calls
no test coverage detected