PageRenderTime 351ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/pct-speedtest.py

https://gitlab.com/grayhamster/pycrypto
Python | 443 lines | 308 code | 73 blank | 62 comment | 71 complexity | 665514e1d1d3a3a5d126c68344205367 MD5 | raw file
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # pct-speedtest.py: Speed test for the Python Cryptography Toolkit
  5. #
  6. # Written in 2009 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  7. #
  8. # ===================================================================
  9. # The contents of this file are dedicated to the public domain. To
  10. # the extent that dedication to the public domain is not available,
  11. # everyone is granted a worldwide, perpetual, royalty-free,
  12. # non-exclusive license to exercise all rights associated with the
  13. # contents of this file for any purpose whatsoever.
  14. # No rights are reserved.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  20. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. # SOFTWARE.
  24. # ===================================================================
  25. import time
  26. import os
  27. import sys
  28. from Crypto.PublicKey import RSA
  29. from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5 as RSAES_PKCS1_v1_5
  30. from Crypto.Signature import PKCS1_PSS, PKCS1_v1_5 as RSASSA_PKCS1_v1_5
  31. from Crypto.Cipher import AES, ARC2, ARC4, Blowfish, CAST, DES3, DES, XOR
  32. from Crypto.Hash import HMAC, MD2, MD4, MD5, SHA224, SHA256, SHA384, SHA512, CMAC
  33. from Crypto.Random import get_random_bytes
  34. import Crypto.Util.Counter
  35. from Crypto.Util.number import bytes_to_long
  36. try:
  37. from Crypto.Hash import SHA1
  38. except ImportError:
  39. # Maybe it's called SHA
  40. from Crypto.Hash import SHA as SHA1
  41. try:
  42. from Crypto.Hash import RIPEMD160
  43. except ImportError:
  44. # Maybe it's called RIPEMD
  45. try:
  46. from Crypto.Hash import RIPEMD as RIPEMD160
  47. except ImportError:
  48. # Some builds of PyCrypto don't have the RIPEMD module
  49. RIPEMD160 = None
  50. try:
  51. import hashlib
  52. import hmac
  53. except ImportError: # Some builds/versions of Python don't have a hashlib module
  54. hashlib = hmac = None
  55. # os.urandom() is less noisy when profiling, but it doesn't exist in Python < 2.4
  56. try:
  57. urandom = os.urandom
  58. except AttributeError:
  59. urandom = get_random_bytes
  60. from Crypto.Random import random as pycrypto_random
  61. import random as stdlib_random
  62. class Benchmark:
  63. def __init__(self):
  64. self.__random_data = None
  65. def random_keys(self, bytes, n=10**5):
  66. """Return random keys of the specified number of bytes.
  67. If this function has been called before with the same number of bytes,
  68. cached keys are used instead of randomly generating new ones.
  69. """
  70. return self.random_blocks(bytes, n)
  71. def random_blocks(self, bytes_per_block, blocks):
  72. bytes = bytes_per_block * blocks
  73. data = self.random_data(bytes)
  74. retval = []
  75. for i in range(blocks):
  76. p = i * bytes_per_block
  77. retval.append(data[p:p+bytes_per_block])
  78. return retval
  79. def random_data(self, bytes):
  80. if self.__random_data is None:
  81. self.__random_data = self._random_bytes(bytes)
  82. return self.__random_data
  83. elif bytes == len(self.__random_data):
  84. return self.__random_data
  85. elif bytes < len(self.__random_data):
  86. return self.__random_data[:bytes]
  87. else:
  88. self.__random_data += self._random_bytes(bytes - len(self.__random_data))
  89. return self.__random_data
  90. def _random_bytes(self, b):
  91. return urandom(b)
  92. def announce_start(self, test_name):
  93. sys.stdout.write("%s: " % (test_name,))
  94. sys.stdout.flush()
  95. def announce_result(self, value, units):
  96. sys.stdout.write("%.2f %s\n" % (value, units))
  97. sys.stdout.flush()
  98. def test_random_module(self, module_name, module):
  99. self.announce_start("%s.choice" % (module_name,))
  100. alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  101. t0 = time.time()
  102. for i in range(5000):
  103. module.choice(alphabet)
  104. t = time.time()
  105. invocations_per_second = 5000 / (t - t0)
  106. self.announce_result(invocations_per_second, "invocations/sec")
  107. def test_pubkey_setup(self, pubkey_name, module, key_bytes):
  108. self.announce_start("%s pubkey setup" % (pubkey_name,))
  109. keys = self.random_keys(key_bytes)[:5]
  110. t0 = time.time()
  111. for k in keys:
  112. module.generate(key_bytes*8)
  113. t = time.time()
  114. pubkey_setups_per_second = len(keys) / (t - t0)
  115. self.announce_result(pubkey_setups_per_second, "Keys/sec")
  116. def test_key_setup(self, cipher_name, module, key_bytes, mode):
  117. self.announce_start("%s key setup" % (cipher_name,))
  118. # Generate random keys for use with the tests
  119. keys = self.random_keys(key_bytes, n=5000)
  120. if hasattr(module, "MODE_CCM") and mode==module.MODE_CCM:
  121. iv = b"\xAA"*8
  122. else:
  123. iv = b"\xAA"*module.block_size
  124. # Perform key setups
  125. if mode is None:
  126. t0 = time.time()
  127. for k in keys:
  128. module.new(k)
  129. t = time.time()
  130. else:
  131. t0 = time.time()
  132. if mode==module.MODE_CTR:
  133. for k in keys:
  134. ctr = Crypto.Util.Counter.new(module.block_size*8,
  135. initial_value=bytes_to_long(iv))
  136. module.new(k, module.MODE_CTR, counter=ctr)
  137. else:
  138. for k in keys:
  139. module.new(k, mode, iv)
  140. t = time.time()
  141. key_setups_per_second = len(keys) / (t - t0)
  142. self.announce_result(key_setups_per_second/1000, "kKeys/sec")
  143. def test_encryption(self, cipher_name, module, key_bytes, mode):
  144. self.announce_start("%s encryption" % (cipher_name,))
  145. # Generate random keys for use with the tests
  146. rand = self.random_data(key_bytes + module.block_size)
  147. key, iv = rand[:key_bytes], rand[key_bytes:]
  148. blocks = self.random_blocks(16384, 1000)
  149. if mode is None:
  150. cipher = module.new(key)
  151. elif mode == "CTR-BE":
  152. from Crypto.Util import Counter
  153. cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size*8, little_endian=False))
  154. elif mode == "CTR-LE":
  155. from Crypto.Util import Counter
  156. cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size*8, little_endian=True))
  157. elif hasattr(module, 'MODE_CCM') and mode==module.MODE_CCM:
  158. cipher = module.new(key, mode, iv[:8], msg_len=len(rand)*len(blocks))
  159. elif mode==module.MODE_CTR:
  160. ctr = Crypto.Util.Counter.new(module.block_size*8,
  161. initial_value=bytes_to_long(iv),
  162. allow_wraparound=True)
  163. cipher = module.new(key, module.MODE_CTR, counter=ctr)
  164. elif mode==module.MODE_ECB:
  165. cipher = module.new(key, module.MODE_ECB)
  166. else:
  167. cipher = module.new(key, mode, iv)
  168. # Perform encryption
  169. t0 = time.time()
  170. for b in blocks:
  171. cipher.encrypt(b)
  172. t = time.time()
  173. encryption_speed = (len(blocks) * len(blocks[0])) / (t - t0)
  174. self.announce_result(encryption_speed / 10**6, "MBps")
  175. def test_hash_small(self, hash_name, hash_constructor, digest_size):
  176. self.announce_start("%s (%d-byte inputs)" % (hash_name, digest_size))
  177. blocks = self.random_blocks(digest_size, 10000)
  178. # Initialize hashes
  179. t0 = time.time()
  180. for b in blocks:
  181. hash_constructor(b).digest()
  182. t = time.time()
  183. hashes_per_second = len(blocks) / (t - t0)
  184. self.announce_result(hashes_per_second / 1000, "kHashes/sec")
  185. def test_hash_large(self, hash_name, hash_constructor, digest_size):
  186. self.announce_start("%s (single large input)" % (hash_name,))
  187. blocks = self.random_blocks(16384, 10000)
  188. # Perform hashing
  189. t0 = time.time()
  190. h = hash_constructor()
  191. for b in blocks:
  192. h.update(b)
  193. h.digest()
  194. t = time.time()
  195. hash_speed = len(blocks) * len(blocks[0]) / (t - t0)
  196. self.announce_result(hash_speed / 10**6, "MBps")
  197. def test_hmac_small(self, mac_name, hmac_constructor, digestmod, digest_size):
  198. keys = iter(self.random_keys(digest_size))
  199. if sys.version_info[0] == 2:
  200. mac_constructor = lambda data=None: hmac_constructor(keys.next(), data, digestmod)
  201. else:
  202. mac_constructor = lambda data=None: hmac_constructor(keys.__next__(), data, digestmod)
  203. self.test_hash_small(mac_name, mac_constructor, digest_size)
  204. def test_hmac_large(self, mac_name, hmac_constructor, digestmod, digest_size):
  205. key = self.random_keys(digest_size)[0]
  206. mac_constructor = lambda data=None: hmac_constructor(key, data, digestmod)
  207. self.test_hash_large(mac_name, mac_constructor, digest_size)
  208. def test_cmac_small(self, mac_name, cmac_constructor, ciphermod, key_size):
  209. keys = iter(self.random_keys(key_size))
  210. if sys.version_info[0] == 2:
  211. mac_constructor = lambda data=None: cmac_constructor(keys.next(), data, ciphermod)
  212. else:
  213. mac_constructor = lambda data=None: cmac_constructor(keys.__next__(), data, ciphermod)
  214. self.test_hash_small(mac_name, mac_constructor, ciphermod.block_size)
  215. def test_cmac_large(self, mac_name, cmac_constructor, ciphermod, key_size):
  216. key = self.random_keys(key_size)[0]
  217. mac_constructor = lambda data=None: cmac_constructor(key, data, ciphermod)
  218. self.test_hash_large(mac_name, mac_constructor, ciphermod.block_size)
  219. def test_pkcs1_sign(self, scheme_name, scheme_constructor, hash_name, hash_constructor, digest_size):
  220. self.announce_start("%s signing %s (%d-byte inputs)" % (scheme_name, hash_name, digest_size))
  221. # Make a key
  222. k = RSA.generate(2048)
  223. sigscheme = scheme_constructor(k)
  224. # Make some hashes
  225. blocks = self.random_blocks(digest_size, 50)
  226. hashes = []
  227. for b in blocks:
  228. hashes.append(hash_constructor(b))
  229. # Perform signing
  230. t0 = time.time()
  231. for h in hashes:
  232. sigscheme.sign(h)
  233. t = time.time()
  234. speed = len(hashes) / (t - t0)
  235. self.announce_result(speed, "sigs/sec")
  236. def test_pkcs1_verify(self, scheme_name, scheme_constructor, hash_name, hash_constructor, digest_size):
  237. self.announce_start("%s verification %s (%d-byte inputs)" % (scheme_name, hash_name, digest_size))
  238. # Make a key
  239. k = RSA.generate(2048)
  240. sigscheme = scheme_constructor(k)
  241. # Make some hashes
  242. blocks = self.random_blocks(digest_size, 50)
  243. hashes = []
  244. for b in blocks:
  245. hashes.append(hash_constructor(b))
  246. # Make some signatures
  247. signatures = []
  248. for h in hashes:
  249. signatures.append(sigscheme.sign(h))
  250. # Double the list, to make timing better
  251. hashes = hashes + hashes
  252. signatures = signatures + signatures
  253. # Perform verification
  254. t0 = time.time()
  255. for h, s in zip(hashes, signatures):
  256. sigscheme.verify(h, s)
  257. t = time.time()
  258. speed = len(hashes) / (t - t0)
  259. self.announce_result(speed, "sigs/sec")
  260. def run(self):
  261. pubkey_specs = [
  262. ("RSA(1024)", RSA, int(1024/8)),
  263. ("RSA(2048)", RSA, int(2048/8)),
  264. ("RSA(4096)", RSA, int(4096/8)),
  265. ]
  266. block_specs = [
  267. ("DES", DES, 8),
  268. ("DES3", DES3, 24),
  269. ("AES128", AES, 16),
  270. ("AES192", AES, 24),
  271. ("AES256", AES, 32),
  272. ("Blowfish(256)", Blowfish, 32),
  273. ("CAST(40)", CAST, 5),
  274. ("CAST(80)", CAST, 10),
  275. ("CAST(128)", CAST, 16),
  276. ]
  277. stream_specs = [
  278. ("ARC2(128)", ARC2, 16),
  279. ("ARC4(128)", ARC4, 16),
  280. ("XOR(24)", XOR, 3),
  281. ("XOR(256)", XOR, 32),
  282. ]
  283. hash_specs = [
  284. ("MD2", MD2),
  285. ("MD4", MD4),
  286. ("MD5", MD5),
  287. ("SHA1", SHA1),
  288. ("SHA224", SHA224),
  289. ("SHA256", SHA256),
  290. ("SHA384", SHA384),
  291. ("SHA512", SHA512),
  292. ]
  293. if RIPEMD160 is not None:
  294. hash_specs += [("RIPEMD160", RIPEMD160)]
  295. hashlib_specs = []
  296. if hashlib is not None:
  297. if hasattr(hashlib, 'md5'): hashlib_specs.append(("hashlib.md5", hashlib.md5))
  298. if hasattr(hashlib, 'sha1'): hashlib_specs.append(("hashlib.sha1", hashlib.sha1))
  299. if hasattr(hashlib, 'sha224'): hashlib_specs.append(("hashlib.sha224", hashlib.sha224))
  300. if hasattr(hashlib, 'sha256'): hashlib_specs.append(("hashlib.sha256", hashlib.sha256))
  301. if hasattr(hashlib, 'sha384'): hashlib_specs.append(("hashlib.sha384", hashlib.sha384))
  302. if hasattr(hashlib, 'sha512'): hashlib_specs.append(("hashlib.sha512", hashlib.sha512))
  303. # stdlib random
  304. self.test_random_module("stdlib random", stdlib_random)
  305. # Crypto.Random.random
  306. self.test_random_module("Crypto.Random.random", pycrypto_random)
  307. # Crypto.PublicKey
  308. for pubkey_name, module, key_bytes in pubkey_specs:
  309. self.test_pubkey_setup(pubkey_name, module, key_bytes)
  310. # Crypto.Cipher (block ciphers)
  311. for cipher_name, module, key_bytes in block_specs:
  312. self.test_key_setup("%s-CBC" % (cipher_name,), module, key_bytes, module.MODE_CBC)
  313. self.test_encryption("%s-CBC" % (cipher_name,), module, key_bytes, module.MODE_CBC)
  314. self.test_encryption("%s-CFB-8" % (cipher_name,), module, key_bytes, module.MODE_CFB)
  315. self.test_encryption("%s-OFB" % (cipher_name,), module, key_bytes, module.MODE_OFB)
  316. self.test_encryption("%s-ECB" % (cipher_name,), module, key_bytes, module.MODE_ECB)
  317. self.test_key_setup("%s-CTR" % (cipher_name,), module, key_bytes, module.MODE_CTR)
  318. self.test_encryption("%s-CTR" % (cipher_name,), module, key_bytes, module.MODE_CTR)
  319. self.test_encryption("%s-OPENPGP" % (cipher_name,), module, key_bytes, module.MODE_OPENPGP)
  320. self.test_encryption("%s-CTR-BE" % (cipher_name,), module, key_bytes, "CTR-BE")
  321. self.test_encryption("%s-CTR-LE" % (cipher_name,), module, key_bytes, "CTR-LE")
  322. if hasattr(module, "MODE_CCM"):
  323. self.test_key_setup("%s-CCM" % (cipher_name,), module, key_bytes, module.MODE_CCM)
  324. self.test_encryption("%s-CCM" % (cipher_name,), module, key_bytes, module.MODE_CCM)
  325. if hasattr(module, "MODE_EAX"):
  326. self.test_key_setup("%s-EAX" % (cipher_name,), module, key_bytes, module.MODE_EAX)
  327. self.test_encryption("%s-EAX" % (cipher_name,), module, key_bytes, module.MODE_EAX)
  328. if hasattr(module, "MODE_GCM"):
  329. self.test_key_setup("%s-GCM" % (cipher_name,), module, key_bytes, module.MODE_GCM)
  330. self.test_encryption("%s-GCM" % (cipher_name,), module, key_bytes, module.MODE_GCM)
  331. # Crypto.Cipher (stream ciphers)
  332. for cipher_name, module, key_bytes in stream_specs:
  333. self.test_key_setup(cipher_name, module, key_bytes, None)
  334. self.test_encryption(cipher_name, module, key_bytes, None)
  335. # Crypto.Hash
  336. for hash_name, module in hash_specs:
  337. self.test_hash_small(hash_name, module.new, module.digest_size)
  338. self.test_hash_large(hash_name, module.new, module.digest_size)
  339. # standard hashlib
  340. for hash_name, func in hashlib_specs:
  341. self.test_hash_small(hash_name, func, func().digest_size)
  342. self.test_hash_large(hash_name, func, func().digest_size)
  343. # PyCrypto HMAC
  344. for hash_name, module in hash_specs:
  345. self.test_hmac_small("HMAC-"+hash_name, HMAC.new, module, module.digest_size)
  346. self.test_hmac_large("HMAC-"+hash_name, HMAC.new, module, module.digest_size)
  347. # standard hmac + hashlib
  348. for hash_name, func in hashlib_specs:
  349. self.test_hmac_small("hmac+"+hash_name, hmac.HMAC, func, func().digest_size)
  350. self.test_hmac_large("hmac+"+hash_name, hmac.HMAC, func, func().digest_size)
  351. # CMAC
  352. for cipher_name, module, key_size in (("AES128", AES, 16),):
  353. self.test_cmac_small(cipher_name+"-CMAC", CMAC.new, module, key_size)
  354. self.test_cmac_large(cipher_name+"-CMAC", CMAC.new, module, key_size)
  355. # PKCS1_v1_5 (sign) + Crypto.Hash
  356. for hash_name, module in hash_specs:
  357. self.test_pkcs1_sign("PKCS#1-v1.5", RSASSA_PKCS1_v1_5.new, hash_name, module.new, module.digest_size)
  358. # PKCS1_PSS (sign) + Crypto.Hash
  359. for hash_name, module in hash_specs:
  360. self.test_pkcs1_sign("PKCS#1-PSS", PKCS1_PSS.new, hash_name, module.new, module.digest_size)
  361. # PKCS1_v1_5 (verify) + Crypto.Hash
  362. for hash_name, module in hash_specs:
  363. self.test_pkcs1_verify("PKCS#1-v1.5", RSASSA_PKCS1_v1_5.new, hash_name, module.new, module.digest_size)
  364. # PKCS1_PSS (verify) + Crypto.Hash
  365. for hash_name, module in hash_specs:
  366. self.test_pkcs1_verify("PKCS#1-PSS", PKCS1_PSS.new, hash_name, module.new, module.digest_size)
  367. if __name__ == '__main__':
  368. Benchmark().run()
  369. # vim:set ts=4 sw=4 sts=4 expandtab: