Skip to content

Instantly share code, notes, and snippets.

@tsing
Forked from fcicq/ed2kHash.py
Created May 28, 2012 15:00
Show Gist options
  • Save tsing/2819614 to your computer and use it in GitHub Desktop.
Save tsing/2819614 to your computer and use it in GitHub Desktop.
ed2kHash class for python
# by fcicq (fcicq at fcicq dot net) @ 2012.5.12, Released under GPLv2
import hashlib
from cStringIO import StringIO
class ed2kHash():
CHUNK_SIZE = 9728000
BLOCK_SIZE = 65536
chunkmd4_list = ''
chunkmd4 = None
chunkpos = 0
def __init__(self, string=''):
self.chunkmd4 = hashlib.new('md4') # I know it will raise ImportError... :D
self.update(string)
def _md4(self, string=''):
return hashlib.new('md4', string)
def _tohex(self, string=''):
return ''.join(["%02x"%ord(x) for x in string])
def update(self, string=''):
l = len(string)
s = StringIO(string)
pos = 0
if not l: return
while pos < l:
blocksize = min(self.CHUNK_SIZE - self.chunkpos, l - pos, self.BLOCK_SIZE)
self.chunkmd4.update(s.read(blocksize))
pos += blocksize
self.chunkpos += blocksize
if self.CHUNK_SIZE == self.chunkpos: # filled just now
self.chunkmd4_list += self.chunkmd4.digest()
self.chunkmd4 = self._md4()
self.chunkpos = 0
s.close()
def digest(self):
if self.chunkmd4_list: # If the first block is not completed, just return the md4 result.
return self._md4(self.chunkmd4_list + self.chunkmd4.digest()).digest()
else:
return self.chunkmd4.digest()
def hexdigest(self):
return self._tohex(self.digest())
def copy(self):
raise NotImplementedError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment