|
18 | 18 | import os
|
19 | 19 | import re
|
20 | 20 | import enum
|
| 21 | +import hashlib |
21 | 22 | from pathlib import Path
|
22 | 23 |
|
23 | 24 | from .exceptions import FileNotFoundException
|
@@ -45,22 +46,24 @@ def detect_hash_algo(checksum_str: str):
|
45 | 46 | hash_len = len(checksum_str)
|
46 | 47 | for name, infos in SUPPORTED_HASH_ALGOS.items():
|
47 | 48 | if infos["LENGTH"] == hash_len:
|
48 |
| - return name |
| 49 | + if validate_checksum_str(checksum_str=checksum_str, hash_algo=name): |
| 50 | + return name |
49 | 51 | else:
|
50 | 52 | raise HashAlgorithmNotSupportedException(
|
51 | 53 | detected_length=hash_len, checksum_str=checksum_str
|
52 | 54 | )
|
53 | 55 |
|
54 | 56 |
|
55 |
| -def validate_checksum_str(checksum_str: str): |
| 57 | +def validate_checksum_str(checksum_str: str, hash_algo: str): |
56 | 58 | """
|
57 | 59 | Checks if the str is a valid checksum in the detected algorithm
|
58 | 60 |
|
59 | 61 | :param checksum_str:the hash string
|
| 62 | + :param hash_algo: the hash algorithm |
60 | 63 | :return: True if valid
|
61 | 64 | :raises HashStrNotValidException: raised if the hash str isn't valid
|
62 | 65 | """
|
63 |
| - hash_name = detect_hash_algo(checksum_str) |
| 66 | + hash_name = hash_algo |
64 | 67 | pattern = re.compile(SUPPORTED_HASH_ALGOS[hash_name]["REX"])
|
65 | 68 | if pattern.match(checksum_str):
|
66 | 69 | return True
|
@@ -92,11 +95,18 @@ def get_file_path_from_str(str_path: str):
|
92 | 95 |
|
93 | 96 |
|
94 | 97 | class IntegrityValidator:
|
95 |
| - def __init__(self, str_path: str): |
| 98 | + def __init__(self, str_path: str, checksum_str: str): |
| 99 | + self.hash_algo = detect_hash_algo(checksum_str=checksum_str) |
| 100 | + self.checksum_str = checksum_str |
96 | 101 | self.file = get_file_path_from_str(str_path)
|
| 102 | + self.hashlib_obj = hashlib.new(self.hash_algo) |
97 | 103 |
|
98 | 104 | def validate_file_integrity(self):
|
99 |
| - pass |
| 105 | + file_checksum = self.get_file_checksum() |
| 106 | + return file_checksum == self.checksum_str |
100 | 107 |
|
101 | 108 | def get_file_checksum(self):
|
102 |
| - pass |
| 109 | + with self.file.open() as file_to_validate: |
| 110 | + file_content = file_to_validate.read() |
| 111 | + self.hashlib_obj.update(file_content) |
| 112 | + return self.hashlib_obj.hexdigest() |
0 commit comments