-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSha.py
52 lines (36 loc) · 1.15 KB
/
Sha.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
48
49
50
51
52
#!/usr/bin/python
#
# Coursera - Cryptography course (crypto-005)
#
# Week 3 - Assignment 1
# Chained blocks hashing
#
from Crypto.Hash import SHA256
# Split a file into smaller chunks
def splitFile(inputFile, chunkSize):
#read the contents of the file
f = open(inputFile, 'rb')
data = f.read() # read the entire content of the file
f.close()
# get the length of data, ie size of the input file in bytes
bytes = len(data)
chunks = []
for i in range(0, bytes+1, chunkSize):
chunks.append(data[i: i+chunkSize])
return chunks
# Hash a file using the specified hash chaining algorithm
def chain_hash(inFile):
chunkSize = 1024 # 1 KB
current_hash = ''
chunks = splitFile(inFile, chunkSize)
for i in range(len(chunks)-1, -1, -1):
sha = SHA256.new(chunks[i])
chunks[i] = chunks[i] + current_hash
sha = SHA256.new(chunks[i])
current_hash = sha.digest()
return current_hash.encode('hex')
if __name__ == "__main__":
target_file = "6.1.intro.mp4_download"
test_file = "6.2.birthday.mp4_download"
print "Chain hash for %s is:\n %s" % (test_file, chain_hash(test_file))
print "Chain hash for %s is:\n %s" % (target_file, chain_hash(target_file))