Uncategorized

eDonkey2000 Hash in Python

As part of a filesystem watcher program I maintain as part of a larger site, I need to obtain the ed2k hash of some files. Believe me when I tell you I have searched high and low for an Edonkey2000 hash algorithm in python. I’ve seen massive libraries that scared the bejesus out of me, but nothing clean, concise, and without external dependencies. Enjoy the below. It’s worth noting it’s just as fast as the C version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import hashlib
 
def hash_file(self, file_path):
    """ Returns the ed2k hash of a given file. """
 
    md4 = hashlib.new('md4').copy
 
    def gen(f):
        while True:
            x = f.read(9728000)
            if x: yield x
            else: return
 
    def md4_hash(data):
        m = md4()
        m.update(data)
        return m
 
    with open(file_path, 'rb') as f:
        a = gen(f)
        hashes = [md4_hash(data).digest() for data in a]
        if len(hashes) == 1:
            return hashes[0].encode("hex")
        else: return md4_hash(reduce(lambda a,d: a + d, hashes, "")).hexdigest()

4 Comments

  1. kerobaros

    This is brilliant, thank you kindly. Is this free to use, as long as there’s attribution?

  2. radicand

    Yes, of course. Enjoy.

  3. hi,
    thank you so much this is great piece of code
    and i can confirm it working !
    you will see it in the near futur in a projekt
    (i will let you know when its public)

    with credit of curse !

    thank you

  4. Thanks for this code – I have adapted it to my animecheck script (https://github.com/OmegaPhil/animecheck) so that it has a mode to read in files and output eD2k links for pasting into AniDB.

Leave a Reply

Your email address will not be published. Required fields are marked *