简体   繁体   中英

Reverse a known algorithm in Python using no third party libraries

I've got a method that hashes an array of integers, shown below:

def digestm(message):
    digest = []
    for i in xrange(0,len(message),1):
        digest.append(0)
        if i != 0:
            digest[i] = ( (129 * message[i]) ^ message[i-1]) % 256
        else:
            digest[i] = ( (129 * message[i]) ^ 0) % 256
    return digest

I want to reverse this algorithm.

Example:

>>>message = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>>digestm(message)
[0, 129, 3, 129, 7, 129, 3, 129, 15, 129, 3, 129, 7, 129, 3, 129]

I want to know how to convert the returned array back into the message array.

Thus far, this is the code I have come up with, but it is definitely not right:

def answer(digest):
    message=[]
    for i in xrange(0,len(digest)-1,1):
        message.append(0)
        if i!= 0:
            message[i] = ((digest[i] ^ digest[i-1])*129)%256
        else:
            message[i] = ((digest[i] ^ 0)*129)%256
    return message

A hash function is a one-way lossy function. You cannot reverse it. The loss takes place due to the modulo % operator. You will lose the quotient (if you will use values greater than 255).

In your case it's just a substitution of values in the same range via a function.

Change

message[i] = ((digest[i] ^ digest[i-1])*129)%256

to

message[i] = ((digest[i] ^ message[i-1])*129)%256

Since during digestm you're XORing the current and the previous plaintext blocks, you have to XOR with the plaintext block and not with the ciphertext block during answer .

Also, you need to remove the -1 in for i in xrange(0,len(digest)-1,1):

This is a pretty bad hash function. Take for example b = 129 * a % 256 :

a => b
0 => 0
1 => 129
2 => 2
3 => 131
4 => 4
5 => 133
...
129 => 1
130 => 130
131 => 2
...

You get the idea. It is perfectly reversible, because it has this property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM