Python : Hash extension attack in python
<p>I want to use h to generate the same md5 as b</p>

<p>Here is the code:</p>

<pre><code>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---&gt; " + a.hexdigest() #9f4bb32ac843d6db979ababa2949cb52
print "want---&gt; " + 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 &gt;&gt; 3) &amp; 0x3f)
    if index &lt; 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 &amp; 0xffffffffL, msg_bits&gt;&gt;32), 8)
</code></pre>

<p>I don't know why the last line couldn't output aba1d6fede83a87d9d6e22bf75974599. 
Is there something wrong with the padding?</p>

<p>This is because the hash you expected (aba1..) is the md5 hash of <code>k + m + x</code> while the hash you got (958a..) is the md5 hash of <code>k + m + padding + x</code>.</p>

<p>The length extension attack lets you generate a hash <code>h2 = md5(k + m + padding + x)</code> based on only knowing the hash <code>h1 = md5(k + m)</code> and the length of the message <code>l = len(k + m)</code>. However, as far as I know, it doesn't let you get rid of the padding between the messages, so you're left with some garbage in between.</p>

python md5