Pre-processing SHA256 Python implementation

不问归期 提交于 2019-12-11 02:59:13

问题


I am working my way through the SHA256 implementation on wikipedia but have came up stuck. I have just tried to write the code for the message pre-processing and my length for the final message is 504 bits, not the 512 required.

Wikipedia: 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)

I'm unsure where the flaw is, I've been over the code quite a few times.

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:


There are two problems:

1) The 488 magic number in your code should be 448.

2) You're only using 16 "bits" (characters) in append_length_of_message().

HIH!



来源:https://stackoverflow.com/questions/24166076/pre-processing-sha256-python-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!