5050 limitations under the License.
5151"""
5252
53+ import hashlib
5354from typing import Optional , Union
5455
55- from cryptography .hazmat .backends import default_backend
56- from cryptography .hazmat .primitives import hashes
57-
5856from PyFunceble .helpers .file import FileHelper
5957
6058
@@ -97,11 +95,12 @@ def algo(self, value: str) -> None:
9795 if not isinstance (value , str ):
9896 raise TypeError (f"<value> should be { str } , { type (value )} given." )
9997
100- value = value .upper ()
98+ value = value .lower ()
10199
102- if not hasattr ( hashes , value ) :
100+ if value not in hashlib . algorithms_available :
103101 raise ValueError (
104- f"<value> ({ value !r} ) in an unknown algorithm ({ self .algo !r} )."
102+ f"<value> ({ value !r} ) in an unknown algorithm "
103+ f"({ hashlib .algorithms_available } )."
105104 )
106105
107106 self ._algo = value
@@ -118,13 +117,6 @@ def set_algo(self, value: str) -> "HashHelper":
118117
119118 return self
120119
121- def __get_hash (self ) -> hashes .Hash :
122- """
123- Provides the Hash to use.
124- """
125-
126- return hashes .Hash (getattr (hashes , self .algo )(), backend = default_backend ())
127-
128120 def hash_file (self , file_path : str ) -> str :
129121 """
130122 Hashes the content of the given file.
@@ -135,7 +127,7 @@ def hash_file(self, file_path: str) -> str:
135127
136128 block_size = 4096
137129
138- digest = self . __get_hash ( )
130+ digest = hashlib . new ( self . algo )
139131
140132 with FileHelper (file_path ).open ("rb" ) as file_stream :
141133 block = file_stream .read (block_size )
@@ -144,7 +136,7 @@ def hash_file(self, file_path: str) -> str:
144136 digest .update (block )
145137 block = file_stream .read (block_size )
146138
147- return digest .finalize (). hex ()
139+ return digest .hexdigest ()
148140
149141 def hash_data (self , data : Union [str , bytes ]) -> str :
150142 """
@@ -163,7 +155,7 @@ def hash_data(self, data: Union[str, bytes]) -> str:
163155 if isinstance (data , str ):
164156 data = data .encode ()
165157
166- digest = self . __get_hash ( )
158+ digest = hashlib . new ( self . algo )
167159 digest .update (data )
168160
169- return digest .finalize (). hex ()
161+ return digest .hexdigest ()
0 commit comments