Inefficient new method from hashlib High

The constructors for the hashlib module are faster than new(). We recommend using hashlib constructors instead.

Detector ID
python/hashlib-constructor@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def constructor_noncompliant():
2    import hashlib
3
4    text = "ExampleString"
5
6    # Noncompliant: uses the new() constructor instead of the hashlib
7    # constructor, which is slower.
8    result = hashlib.new('sha256', text.encode())
9
10    print("The hexadecimal equivalent of SHA256 is : ")
11    print(result.hexdigest())

Compliant example

1def constructor_compliant():
2    import hashlib
3
4    text = "ExampleString"
5
6    # Compliant: uses the hashlib constructor over the new(), which is faster.
7    result = hashlib.sha256(text.encode())
8
9    print("The hexadecimal equivalent of SHA256 is : ")
10    print(result.hexdigest())