预处理 SHA256 Python 实现 [英] Pre-processing SHA256 Python implementation

查看:65
本文介绍了预处理 SHA256 Python 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过维基百科上的 SHA256 实现工作,但卡住了.我刚刚尝试编写消息预处理的代码,最终消息的长度是 504 位,而不是所需的 512.

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.

维基百科:SHA256

预处理:

将位1"附加到消息中

附加 k 位0",其中 k 是最小数 >= 0,这样得到的消息长度(以位为模 512)为 448.

append k bits '0', where k is the minimum number >= 0 such that the resulting message length (modulo 512 in bits) is 448.

附加消息的长度(不带 '1' 位或填充),以位为单位,作为 64 位大端整数(这将使整个后处理长度成为 512 位的倍数)

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) 代码中的 488 幻数应该是 448.

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

2) 您在 append_length_of_message() 中只使用了 16 个位"(字符).

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

嗨!

这篇关于预处理 SHA256 Python 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆