-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalwareAnalysis.py
More file actions
57 lines (41 loc) · 2.11 KB
/
malwareAnalysis.py
File metadata and controls
57 lines (41 loc) · 2.11 KB
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
53
54
55
56
57
import hashlib
# a hashlib library for cryptographic hashing functionality.
# This line brings in the hashing functions to calculate the MD5 hash
# essential for computing the MD5 hash of a file.
def calculate_md5(filename):
# defines a Python function named 'calculate_md5' that takes a filename
# as a parameter
# it will calculate the MD5 has for the specified file
# defines core functionality of the script
try:
md5_hash = hashlib.md5() # initializes an MD5 object. Line creates an instance of of the MD5 hash object
# we"ll use MD5 to update and calculate the hash
with open(filename, 'rb') as file:
# opens the specified file in binary read mode, creates a context manager to ensure file is close.
# this prepares for the reading file contents
# starts an infinite loop. Sets up loop to read the file in chunks
while True:
data = file.read(8192)
# function reads up to 8192(8KB) of data from the file. Reads a chunk of data from the file into the
# 'data' variable allows for processing of the file in manageable chunks
if not data:
# checks if 'data' variable is empty, indicating it's reached the end of the file
# helps exit the loop when end of file is reached
break
md5_hash.update(data)
# updates the MD5 hash object with the current chunk of data. Line includes the chunk of data in the hash
# calculation incorporates the file's contents into the MD5 hash calculation
return md5_hash.hexdigest()
# returns the hexadecimal representation of the MD% hash
# calculates final MD5 hash, returns it as a hexadecimal string
# provides the computed MD5 as a result of the function
except Exception as e:
print(f"Error calculating MD5 hash: {str(e)}")
return None
if __name__ == '__main__':
filename = "sample.exe"
md5 = calculate_md5(filename)
if md5:
print(f"MD5 hash: {md5}")
else:
print("Error calculating MD5 hash.")