Created
December 29, 2022 14:06
-
-
Save bbjubjub2494/3ad857f34ba9535484d38ab378b77e32 to your computer and use it in GitHub Desktop.
SHA-1 implementation produced by ChatGPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
def sha1(data): | |
""" | |
Implementation of the SHA-1 hash function in pure Python. | |
""" | |
# Initialize variables | |
h0 = 0x67452301 | |
h1 = 0xEFCDAB89 | |
h2 = 0x98BADCFE | |
h3 = 0x10325476 | |
h4 = 0xC3D2E1F0 | |
# Pre-processing | |
original_byte_len = len(data) | |
original_bit_len = original_byte_len * 8 | |
data += b'\x80' | |
data += b'\x00' * ((56 - (original_byte_len + 1) % 64) % 64) | |
data += struct.pack('>Q', original_bit_len) | |
# Process the message in successive 512-bit chunks | |
for i in range(0, len(data), 64): | |
w = [0] * 80 | |
for j in range(16): | |
w[j] = struct.unpack('>I', data[i + j*4:i + j*4 + 4])[0] | |
for j in range(16, 80): | |
w[j] = left_rotate((w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]), 1) | |
# Initialize hash value for this chunk | |
a = h0 | |
b = h1 | |
c = h2 | |
d = h3 | |
e = h4 | |
# Main loop | |
for i in range(80): | |
if 0 <= i <= 19: | |
f = (b & c) | (~b & d) | |
k = 0x5A827999 | |
elif 20 <= i <= 39: | |
f = b ^ c ^ d | |
k = 0x6ED9EBA1 | |
elif 40 <= i <= 59: | |
f = (b & c) | (b & d) | (c & d) | |
k = 0x8F1BBCDC | |
elif 60 <= i <= 79: | |
f = b ^ c ^ d | |
k = 0xCA62C1D6 | |
a, b, c, d, e = ((left_rotate(a, 5) + f + e + k + w[i]) & 0xffffffff, | |
a, left_rotate(b, 30), c, d) | |
# Add this chunk's hash to result so far | |
h0 = (h0 + a) & 0xffffffff | |
h1 = (h1 + b) & 0xffffffff | |
h2 = (h2 + c) & 0xffffffff | |
h3 = (h3 + d) & 0xffffffff | |
h4 = (h4 + e) & 0xffffffff | |
# Produce the final hash value (big-endian) | |
return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4) | |
def left_rotate(n, b): | |
""" | |
Left rotate a 32-bit unsigned integer n by b bits. | |
""" | |
return ((n << b) | (n >> (32 - b))) & 0xffffffff |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sha1 import sha1 | |
import hashlib | |
TEST_VECTOR = b'', b'test', b'aaaaaaabaaacaaadaaaeaaafaaag' | |
for t in TEST_VECTOR: | |
assert sha1(b"test") == hashlib.sha1(b"test").hexdigest() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment