Added pytests to hashes/md5.py (#1100)

* Added pytests to sha1.py

* tweaking md5

* Added Pytests to hashes/md5.py
This commit is contained in:
QuantumNovice 2019-08-06 16:16:30 +05:00 committed by Harshil
parent 89acf5d017
commit d21b4cfb48

View File

@ -1,6 +1,7 @@
from __future__ import print_function
import math
def rearrange(bitString32):
"""[summary]
Regroups the given binary string.
@ -13,6 +14,8 @@ def rearrange(bitString32):
Returns:
[string] -- [32 bit binary string]
>>> rearrange('1234567890abcdfghijklmnopqrstuvw')
'pqrstuvwhijklmno90abcdfg12345678'
"""
if len(bitString32) != 32:
@ -22,12 +25,15 @@ def rearrange(bitString32):
newString += bitString32[8*i:8*i+8]
return newString
def reformatHex(i):
"""[summary]
Converts the given integer into 8-digit hex number.
Arguments:
i {[int]} -- [integer]
>>> reformatHex(666)
'9a020000'
"""
hexrep = format(i, '08x')
@ -36,6 +42,7 @@ def reformatHex(i):
thing += hexrep[2*i:2*i+2]
return thing
def pad(bitString):
"""[summary]
Fills up the binary string to a 512 bit binary string
@ -46,7 +53,6 @@ def pad(bitString):
Returns:
[string] -- [binary string]
"""
startLength = len(bitString)
bitString += '1'
while len(bitString) % 512 != 448:
@ -55,6 +61,7 @@ def pad(bitString):
bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32])
return bitString
def getBlock(bitString):
"""[summary]
Iterator:
@ -74,7 +81,12 @@ def getBlock(bitString):
yield mySplits
currPos += 512
def not32(i):
'''
>>> not32(34)
4294967261
'''
i_str = format(i, '032b')
new_str = ''
for c in i_str:
@ -82,11 +94,15 @@ def not32(i):
return int(new_str, 2)
def sum32(a, b):
'''
'''
return (a + b) % 2**32
def leftrot32(i, s):
return (i << s) ^ (i >> (32-s))
def md5me(testString):
"""[summary]
Returns a 32-bit hash code of the string 'testString'
@ -107,7 +123,7 @@ def md5me(testString):
c0 = 0x98badcfe
d0 = 0x10325476
s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, \
s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, \
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, \
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ]
@ -142,14 +158,19 @@ def md5me(testString):
c0 = sum32(c0, C)
d0 = sum32(d0, D)
digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0)
digest = reformatHex(a0) + reformatHex(b0) + \
reformatHex(c0) + reformatHex(d0)
return digest
def test():
assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e"
assert md5me("The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6"
assert md5me(
"The quick brown fox jumps over the lazy dog") == "9e107d9d372bb6826bd81d3542a419d6"
print("Success.")
if __name__ == "__main__":
test()
import doctest
doctest.testmod()