You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ed2khash.py 863B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. ''' implementation of ed2k-hashing in python. original code stolen from
  3. http://www.radicand.org/blog/orz/2010/2/21/edonkey2000-hash-in-python/'''
  4. import hashlib
  5. import os.path
  6. from functools import reduce
  7. _md4 = hashlib.new('md4').copy
  8. def _chuncks(f):
  9. while True:
  10. x = f.read(9728000)
  11. if x:
  12. yield x
  13. else:
  14. return
  15. def _md4_hash(data):
  16. m = _md4()
  17. m.update(data)
  18. return m
  19. def hash(file):
  20. """ Returns the ed2k hash of the given file. """
  21. hashes = [_md4_hash(data) for data in _chuncks(file)]
  22. if len(hashes) == 1:
  23. return hashes[0].hexdigest()
  24. else:
  25. return _md4_hash(
  26. reduce(lambda a, b: a + b.digest(), hashes, b'')
  27. ).hexdigest()
  28. def link(file):
  29. """ Returns the ed2k link of the given file. """
  30. return "ed2k://|file|%s|%d|%s|" % (
  31. os.path.basename(file.name),
  32. os.path.getsize(file.name),
  33. hash(file)
  34. )