-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHashingFile.py
More file actions
90 lines (71 loc) · 2.97 KB
/
HashingFile.py
File metadata and controls
90 lines (71 loc) · 2.97 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
File: HashingFile.py
Authors:
- Amey Thakur (https://github.com/Amey-Thakur)
- Mega Satish (https://github.com/msatmod)
Repository: https://github.com/Amey-Thakur/PYTHON-SHORTS
Release Date: January 9, 2022
License: MIT License
Description:
A cryptographic utility for calculating the hash sum of files. This module
implements a stream-based hashing mechanism using the Merkle–Damgård
construction, enabling efficient integrity verification of large
datasets with minimal memory overhead.
Mathematical Logic:
A cryptographic hash function H maps arbitrary-sized data to a fixed-size
bit string. This implementation ensures determinism and collision resistance
by processing file contents in discrete blocks (B-byte chunks).
"""
import hashlib
import os
from typing import Optional
class FileHasher:
"""Scholarly implementation of a stream-based cryptographic file hashing service."""
def __init__(self, block_size: int = 65536):
self.block_size = block_size
def calculate_hash(self, file_path: str, algorithm: str = 'sha256') -> str:
"""
Computes the digest of a file using a streaming buffer.
Args:
file_path (str): Absolute or relative path to the target file.
algorithm (str): The hash algorithm to employ (e.g., 'sha256', 'md5').
Returns:
str: The hexadecimal representation of the digest.
Raises:
FileNotFoundError: If the specified file does not exist.
ValueError: If the requested algorithm is not supported.
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"File system error: Resource not found at {file_path}")
try:
hasher = hashlib.new(algorithm)
except ValueError:
raise ValueError(f"Cryptographic error: Algorithm '{algorithm}' is unsupported.")
with open(file_path, 'rb') as f:
while True:
buffer = f.read(self.block_size)
if not buffer:
break
hasher.update(buffer)
return hasher.hexdigest()
def run_hashing_demo():
"""Execution demo for verifying file integrity via cryptographic digests."""
print("--- Python Shorts: Cryptographic Hash Functions & Integrity ---")
# Create a temporary verification artifact
temp_file = "integrity_test.txt"
with open(temp_file, "w") as f:
f.write("Python Shorts: Scholarly Hashing Demonstration.")
hasher = FileHasher()
try:
print(f"\n[Target]: {temp_file}")
sha256_sum = hasher.calculate_hash(temp_file, 'sha256')
print(f"[SHA-256]: {sha256_sum}")
md5_sum = hasher.calculate_hash(temp_file, 'md5')
print(f"[MD5]: {md5_sum}")
except Exception as e:
print(f"[Error]: {e}")
finally:
if os.path.exists(temp_file):
os.remove(temp_file)
if __name__ == "__main__":
run_hashing_demo()