Skip to content

Commit 871a0a0

Browse files
committed
no need for complications
1 parent 7f5a2a9 commit 871a0a0

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

sha256.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
from unittest import TextTestRunner
33
from sys import argv
4+
45
from constants import INITIAL_HASH_VALUES, CONSTANTS
56
from helpers import bytes_to_words, words_to_bytes, circular_shift
67
from test_project import make_test_suite
@@ -14,7 +15,7 @@ def pad_message(byte_message: bytes):
1415
and then 0 value bytes
1516
At the end of the message adds 64b/8B containing length(in bits) of original message
1617
"""
17-
number_of_zeros = 64 - ((len(byte_message) + 8) & 0x3F) - 1
18+
number_of_zeros = 64 - ((len(byte_message) + 8) % 64) - 1
1819
byte_message += (
1920
b"\x80"
2021
+ b"\x00" * (number_of_zeros)
@@ -49,9 +50,9 @@ def sha256_bytes(message: bytes, in_hex=True):
4950
Ch = lambda x, y, z: z ^ (x & (y ^ z)) # Choose function
5051
Maj = lambda x, y, z: ((x | y) & z) | (x & y) # Majority function
5152

52-
def _round(hash_values: tuple, word: int, constant: int):
53+
def _round(working_variables: tuple, word: int, constant: int):
5354
# Function performing one round of the compression function
54-
a, b, c, d, e, f, g, h = hash_values
55+
a, b, c, d, e, f, g, h = working_variables
5556
temp1 = h + sigma1(e) + Ch(e, f, g) + constant + word
5657
temp2 = sigma0(a) + Maj(a, b, c)
5758
return (
@@ -75,20 +76,20 @@ def _round(hash_values: tuple, word: int, constant: int):
7576
for chunk in chunks:
7677
# Initializing values for the current loop
7778
W = chunk[:]
78-
current_hash_values = hash_values
79+
working_variables = hash_values
7980

8081
# Extend chunks onto the whole range
8182
for i in range(16, 64):
8283
W.append(
8384
(W[i - 16] + sum0(W[i - 15]) + W[i - 7] + sum1(W[i - 2])) & 0xFFFFFFFF
8485
)
85-
86+
8687
# Compression loop
8788
for i in range(64):
88-
current_hash_values = _round(current_hash_values, W[i], CONSTANTS[i])
89+
working_variables = _round(working_variables, W[i], CONSTANTS[i])
8990

9091
hash_values = tuple(
91-
[(current_hash_values[i] + hash_values[i]) & 0xFFFFFFFF for i in range(8)]
92+
[(working_variables[i] + hash_values[i]) & 0xFFFFFFFF for i in range(8)]
9293
)
9394
result = words_to_bytes(hash_values)
9495
if in_hex:
@@ -97,7 +98,7 @@ def _round(hash_values: tuple, word: int, constant: int):
9798
return result
9899

99100

100-
def sha256_from_file(filename):
101+
def sha256_from_file(filename: str):
101102
"""
102103
Read file bytes and hashes them
103104
"""

0 commit comments

Comments
 (0)