forked from nicoddemus/ss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculate_hash.py
47 lines (35 loc) · 1.41 KB
/
calculate_hash.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import struct
import os
#===================================================================================================
# CalculateHashForFile
#===================================================================================================
def CalculateHashForFile(name):
'''
Calculates the hash for the given filename.
Algorithm from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes
@param name: str
Path to the file
@return: str
The calculated hash code, as an hex string.
'''
longlongformat = 'q' # long long
bytesize = struct.calcsize(longlongformat)
f = open(name, "rb")
filesize = os.path.getsize(name)
hash = filesize
if filesize < 65536 * 2:
return "SizeError"
for x in range(65536/bytesize):
buffer = f.read(bytesize)
(l_value,)= struct.unpack(longlongformat, buffer)
hash += l_value
hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number
f.seek(max(0,filesize-65536),0)
for x in range(65536/bytesize):
buffer = f.read(bytesize)
(l_value,)= struct.unpack(longlongformat, buffer)
hash += l_value
hash = hash & 0xFFFFFFFFFFFFFFFF
f.close()
returnedhash = "%016x" % hash
return returnedhash