Skip to content

Commit

Permalink
Get rid of cryptography - as dependency.
Browse files Browse the repository at this point in the history
This patch touches #401.
This patch touches #381.

cc: @Nilsonfsilva @DandelionSprout
  • Loading branch information
funilrys committed Nov 5, 2024
1 parent 45d932b commit a781c05
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 19 deletions.
26 changes: 9 additions & 17 deletions PyFunceble/helpers/hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,9 @@
limitations under the License.
"""

import hashlib
from typing import Optional, Union

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

from PyFunceble.helpers.file import FileHelper


Expand Down Expand Up @@ -97,11 +95,12 @@ def algo(self, value: str) -> None:
if not isinstance(value, str):
raise TypeError(f"<value> should be {str}, {type(value)} given.")

value = value.upper()
value = value.lower()

if not hasattr(hashes, value):
if value not in hashlib.algorithms_available:
raise ValueError(
f"<value> ({value!r}) in an unknown algorithm ({self.algo!r})."
f"<value> ({value!r}) in an unknown algorithm "
f"({hashlib.algorithms_available})."
)

self._algo = value
Expand All @@ -118,13 +117,6 @@ def set_algo(self, value: str) -> "HashHelper":

return self

def __get_hash(self) -> hashes.Hash:
"""
Provides the Hash to use.
"""

return hashes.Hash(getattr(hashes, self.algo)(), backend=default_backend())

def hash_file(self, file_path: str) -> str:
"""
Hashes the content of the given file.
Expand All @@ -135,7 +127,7 @@ def hash_file(self, file_path: str) -> str:

block_size = 4096

digest = self.__get_hash()
digest = hashlib.new(self.algo)

with FileHelper(file_path).open("rb") as file_stream:
block = file_stream.read(block_size)
Expand All @@ -144,7 +136,7 @@ def hash_file(self, file_path: str) -> str:
digest.update(block)
block = file_stream.read(block_size)

return digest.finalize().hex()
return digest.hexdigest()

def hash_data(self, data: Union[str, bytes]) -> str:
"""
Expand All @@ -163,7 +155,7 @@ def hash_data(self, data: Union[str, bytes]) -> str:
if isinstance(data, str):
data = data.encode()

digest = self.__get_hash()
digest = hashlib.new(self.algo)
digest.update(data)

return digest.finalize().hex()
return digest.hexdigest()
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
alembic
colorama
cryptography>=42.0
dnspython[DOH]~=2.6.0
domain2idna~=1.12.0
inflection
Expand Down
1 change: 0 additions & 1 deletion requirements.win.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
alembic
colorama
cryptography>=42.0
dnspython[DOH]~=2.6.0
domain2idna~=1.12.0
inflection
Expand Down

0 comments on commit a781c05

Please sign in to comment.