MD5 to long?

Anton Vredegoor anton at vredegoor.doge.nl
Sat Apr 26 21:14:21 CEST 2003


Axel Grune <NineOfSix at gmx.de> wrote:

>Hi, is there any function which can convert a MD5 or SHA1 sum
>(e.g. fd4cef7a4e607f1fcc920ad6329a6df2df99a4e8) to a long integer?

MD5 or SHA do have digest() and also hexdigest(). I couldn't find sum.
Digest returns bytes and hexdigest returns a string of hexadecimal
digits. It seems *very* unlikely that the sequence you are giving is a
digest and others have already presented solutions based on the
hypothesis that it is a hexdigest. However, since it is not 100%
certain that it is not a digest, and because possibly a more flexible
approach can still be interesting even if it is a hexdigest, I would
like to present a class which just ranks a list. It is unlikely that a
MD5 (check?) sum will be used for integer arithmetic so it shouldn't
matter that the mapping is unconventional. The class is halfway on its
way to its final release so please test it extensively but don't use
it for production code.

Anton

class Rank:
    
    """ 
        ranks and unranks lists, it has to be initialized with a 
        reference list wherein each item occurs once
    """
    
    def __init__(self,items):
        #initialize with reference list
        self.items, self.base = items, len(items)

    def unrank(self,n):
        #create the list with rank n
        result, base, items = [], self.base, self.items
        while n >= 0:
            i = (n-base)/base
            result.append(items[n-base*(i+1)])
            n = i
        result.reverse()
        return result

    def rank(self,L):
        #compute the rank of list L
        index, base = self.items.index, self.base
        i = index(L[0])
        for x in L[1:]:  i =  index(x)+base*(i+1)
        return i

def test():
    str = """I am the giant Caraculiambro, lord of the island of
Malindrania, vanquished in single combat by the never sufficiently
extolled knight Don Quixote of La Mancha, who has commanded me to
present myself before your Grace, that your Highness dispose of me
at your pleasure"""

    import md5
    R = Rank([chr(i) for i in range(256)])
    dgst = md5.new(str).digest()
    idx = R.rank(dgst)
    assert  ''.join(R.unrank(idx))==dgst
    print "%s\n\n%s" %(str,idx)

if __name__=='__main__':
    test()





More information about the Python-list mailing list