pycryptodome icon indicating copy to clipboard operation
pycryptodome copied to clipboard

SHA512 from Cryptodome.Hash slower than sha512 from hashlib

Open vstoykovbg opened this issue 5 years ago • 1 comments

Example code:

#!/usr/bin/python3

from hashlib import sha512
from Cryptodome.Hash import SHA512
import time

initial_digest=b'test.test.test.test.test'
iterations=500000

# *******************

digest=initial_digest

start = time.time()

for counter in range(iterations):
    digest=sha512(digest).digest()


end = time.time()
print("  Time (hashlib sha512):\t", end - start)

# *******************

digest=initial_digest

start = time.time()

for counter in range(iterations):
    digest=SHA512.new(data=digest).digest()


end = time.time()
print("Time (cryptodome sha512):\t", end - start)


# *******************

digest=initial_digest

start = time.time()

MySHA512=SHA512.new

for counter in range(iterations):
    digest=MySHA512(data=digest).digest()


end = time.time()
print("Time (cryptodome sha512):\t", end - start)

Output on my computer:

valentin@computer:~/python/test3$ ./test-sha512.py
  Time (hashlib sha512):	 0.5348014831542969
Time (cryptodome sha512):	 7.416509389877319
Time (cryptodome sha512):	 7.28940749168396
valentin@computer:~/python/test3$ ./test-sha512.py
  Time (hashlib sha512):	 0.5275444984436035
Time (cryptodome sha512):	 7.590082168579102
Time (cryptodome sha512):	 7.583686351776123
valentin@computer:~/python/test3$ ./test-sha512.py
  Time (hashlib sha512):	 0.5171098709106445
Time (cryptodome sha512):	 7.440552234649658
Time (cryptodome sha512):	 7.221668243408203
valentin@computer:~/python/test3$ 

Is this because of Cryptodome using more object oriented approach? Or the underlying implementation of the algorithm is somehow inefficient?

vstoykovbg avatar Nov 18 '19 17:11 vstoykovbg

Please see https://github.com/Legrandin/pycryptodome/issues/277.

Legrandin avatar Nov 18 '19 17:11 Legrandin

Is there any reason to ever prefer Cryptodome's hash functions over hashlib then?

0xallie avatar Jan 19 '23 19:01 0xallie

A couple reasons:

  • A few other functions in pycryptodome want a hash object created with pycryptodome.
  • pycryptodome supports more different kinds of hashes than the standard library.

If all you want to do is to get a sha512 hash as string or bytes, you don't need pycryptodome's hash functions.

Akuli avatar Jan 21 '23 12:01 Akuli