Python:python中的哈希扩展攻击

时间:2016-10-09 22:09:06

标签: python md5

我想用h生成与b

相同的md5

以下是代码:

k = "secret"
m = "show me the grade"
m2 = "show me the grade and change it to 100"
x = " and change it to 100"
a = md5(k + m)
b = md5(k + m2)
print "have---> " + a.hexdigest() #9f4bb32ac843d6db979ababa2949cb52
print "want---> " + b.hexdigest() #aba1d6fede83a87d9d6e22bf75974599

h = md5(state="9f4bb32ac843d6db979ababa2949cb52".decode("hex"),count=512)
h.update(x)

print h.hexdigest() # these two lines get 958acc96a173fd4d7571ac365db06f65
print md5((k + m + padding(len(k + m)*8))+ x).hexdigest()

def padding(msg_bits):
    """padding(msg_bits) - Generates the padding that should be
    appended to the end of a message of the given size to reach
    a multiple of the block size."""

    index = int((msg_bits >> 3) & 0x3f)
    if index < 56:
        padLen = (56 - index)
    else:
        padLen = (120 - index)

    # (the last 8 bytes store the number of bits in the message)
    return PADDING[:padLen] + _encode((msg_bits & 0xffffffffL, msg_bits>>32), 8)

我不知道为什么最后一行无法输出aba1d6fede83a87d9d6e22bf75974599。 填充是否有问题?

1 个答案:

答案 0 :(得分:0)

这是因为您期望的哈希值(aba1 ..)是k + m + x的md5哈希值,而您获得的哈希值(958a ..)是k + m + padding + x的md5哈希值。

长度扩展攻击允许您基于仅知道哈希h2 = md5(k + m + padding + x)和消息h1 = md5(k + m)的长度来生成哈希l = len(k + m)。但是,据我所知,它不会让你摆脱消息之间的填充,所以你之间留下了一些垃圾。