27 lines
907 B
Python
27 lines
907 B
Python
import hashlib
|
|
from pathlib import Path
|
|
|
|
|
|
class IntegrityChecker:
|
|
"""
|
|
Класс для проверки целостности файлов по хэш-сумме.
|
|
"""
|
|
|
|
def calculate_hash(self, file_path: str) -> str:
|
|
hasher = hashlib.sha256()
|
|
with open(file_path, "rb") as f:
|
|
for chunk in iter(lambda: f.read(4096), b""):
|
|
hasher.update(chunk)
|
|
return hasher.hexdigest()
|
|
|
|
def save_hash(self, file_path: str, hash_file: str) -> None:
|
|
file_hash = self.calculate_hash(file_path)
|
|
Path(hash_file).write_text(file_hash, encoding="utf-8")
|
|
|
|
def verify_hash(self, file_path: str, hash_file: str) -> bool:
|
|
if not Path(hash_file).exists():
|
|
return False
|
|
expected = Path(hash_file).read_text(encoding="utf-8").strip()
|
|
actual = self.calculate_hash(file_path)
|
|
return expected == actual
|