我正在维基百科上完成 SHA256 的实现,但遇到了困难。我刚刚尝试编写消息预处理的代码,最终消息的长度是 504 位,而不是所需的 512 位。
维基百科:SHA256
Pre-processing:
append the bit '1' to the message
append k bits '0', where k is the minimum number >= 0 such that the resulting message length (modulo 512 in bits) is 448.
append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer (this will make the entire post-processed length a multiple of 512 bits)
我不确定缺陷在哪里,我已经检查过代码好几次了。
def joe_sha256 ( input_string ):
"Joe's SHA256 implementation"
# Create a binary version of the input string
binary_string = create_binary ( input_string )
# Append '1' bit to the end as per the SHA256 specification
appended_1_bit_string = append_bit_1 ( binary_string )
# Append 'k' bits to allow for len(string) % 512 == 488
appended_k_string = append_k_bit ( appended_1_bit_string )
# Append length of message
length_of_message = append_length_of_message ( binary_string )
# Create final message
final_message = appended_k_string + length_of_message
print(len(final_message)) # This prints out 504, it should be 512!!!!
return final_message # Just for testing.
def create_binary ( input_string ):
"Takes a string and outputs its binary form"
A = ''.join(format(ord(x), 'b').zfill(8) for x in input_string)
return A
def append_bit_1 ( input_string ):
"Appends the bit 1 to the binary form"
input_string = input_string + '1'
return input_string
def append_k_bit ( input_string ):
"Makes sure the length of input will become X % 512 == 488"
if len(input_string) % 512 == 488:
return input_string
else:
while len(input_string) % 512 != 488:
input_string = input_string + '0'
return input_string
def append_length_of_message ( input_string ):
""
# Get value
hex = format(len(input_string),'x')
# Construct the 64 bit number?
final_num = ''
length = 16-len(hex)
for x in range(length):
final_num = final_num + '0'
final_num = final_num + hex
return final_num
最佳答案
有两个问题:
1) 代码中的 488 魔数(Magic Number)应该是 448。
2) 您在append_length_of_message() 中只使用了16 个“位”(字符)。
嗨!
关于python - 预处理 SHA256 Python 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166076/