You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

826 lines
27 KiB

  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <algorithm>
  15. #include <string>
  16. #include <functional>
  17. #include <memory>
  18. #include <vector>
  19. #include <assert.h>
  20. #include <stdint.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <openssl/aead.h>
  24. #include <openssl/bn.h>
  25. #include <openssl/curve25519.h>
  26. #include <openssl/digest.h>
  27. #include <openssl/err.h>
  28. #include <openssl/ec.h>
  29. #include <openssl/ecdsa.h>
  30. #include <openssl/ec_key.h>
  31. #include <openssl/evp.h>
  32. #include <openssl/nid.h>
  33. #include <openssl/rand.h>
  34. #include <openssl/rsa.h>
  35. #if defined(OPENSSL_WINDOWS)
  36. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  37. #include <windows.h>
  38. OPENSSL_MSVC_PRAGMA(warning(pop))
  39. #elif defined(OPENSSL_APPLE)
  40. #include <sys/time.h>
  41. #else
  42. #include <time.h>
  43. #endif
  44. #include "../crypto/internal.h"
  45. #include "internal.h"
  46. // TimeResults represents the results of benchmarking a function.
  47. struct TimeResults {
  48. // num_calls is the number of function calls done in the time period.
  49. unsigned num_calls;
  50. // us is the number of microseconds that elapsed in the time period.
  51. unsigned us;
  52. void Print(const std::string &description) {
  53. printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
  54. description.c_str(), us,
  55. (static_cast<double>(num_calls) / us) * 1000000);
  56. }
  57. void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
  58. printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
  59. num_calls, description.c_str(), us,
  60. (static_cast<double>(num_calls) / us) * 1000000,
  61. static_cast<double>(bytes_per_call * num_calls) / us);
  62. }
  63. };
  64. #if defined(OPENSSL_WINDOWS)
  65. static uint64_t time_now() { return GetTickCount64() * 1000; }
  66. #elif defined(OPENSSL_APPLE)
  67. static uint64_t time_now() {
  68. struct timeval tv;
  69. uint64_t ret;
  70. gettimeofday(&tv, NULL);
  71. ret = tv.tv_sec;
  72. ret *= 1000000;
  73. ret += tv.tv_usec;
  74. return ret;
  75. }
  76. #else
  77. static uint64_t time_now() {
  78. struct timespec ts;
  79. clock_gettime(CLOCK_MONOTONIC, &ts);
  80. uint64_t ret = ts.tv_sec;
  81. ret *= 1000000;
  82. ret += ts.tv_nsec / 1000;
  83. return ret;
  84. }
  85. #endif
  86. static uint64_t g_timeout_seconds = 1;
  87. static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
  88. // total_us is the total amount of time that we'll aim to measure a function
  89. // for.
  90. const uint64_t total_us = g_timeout_seconds * 1000000;
  91. uint64_t start = time_now(), now, delta;
  92. unsigned done = 0, iterations_between_time_checks;
  93. if (!func()) {
  94. return false;
  95. }
  96. now = time_now();
  97. delta = now - start;
  98. if (delta == 0) {
  99. iterations_between_time_checks = 250;
  100. } else {
  101. // Aim for about 100ms between time checks.
  102. iterations_between_time_checks =
  103. static_cast<double>(100000) / static_cast<double>(delta);
  104. if (iterations_between_time_checks > 1000) {
  105. iterations_between_time_checks = 1000;
  106. } else if (iterations_between_time_checks < 1) {
  107. iterations_between_time_checks = 1;
  108. }
  109. }
  110. for (;;) {
  111. for (unsigned i = 0; i < iterations_between_time_checks; i++) {
  112. if (!func()) {
  113. return false;
  114. }
  115. done++;
  116. }
  117. now = time_now();
  118. if (now - start > total_us) {
  119. break;
  120. }
  121. }
  122. results->us = now - start;
  123. results->num_calls = done;
  124. return true;
  125. }
  126. static bool SpeedRSA(const std::string &selected) {
  127. if (!selected.empty() && selected.find("RSA") == std::string::npos) {
  128. return true;
  129. }
  130. static const struct {
  131. const char *name;
  132. const uint8_t *key;
  133. const size_t key_len;
  134. } kRSAKeys[] = {
  135. {"RSA 2048", kDERRSAPrivate2048, kDERRSAPrivate2048Len},
  136. {"RSA 4096", kDERRSAPrivate4096, kDERRSAPrivate4096Len},
  137. };
  138. for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kRSAKeys); i++) {
  139. const std::string name = kRSAKeys[i].name;
  140. bssl::UniquePtr<RSA> key(
  141. RSA_private_key_from_bytes(kRSAKeys[i].key, kRSAKeys[i].key_len));
  142. if (key == nullptr) {
  143. fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
  144. ERR_print_errors_fp(stderr);
  145. return false;
  146. }
  147. std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key.get())]);
  148. const uint8_t fake_sha256_hash[32] = {0};
  149. unsigned sig_len;
  150. TimeResults results;
  151. if (!TimeFunction(&results,
  152. [&key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
  153. // Usually during RSA signing we're using a long-lived |RSA| that has
  154. // already had all of its |BN_MONT_CTX|s constructed, so it makes
  155. // sense to use |key| directly here.
  156. return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
  157. sig.get(), &sig_len, key.get());
  158. })) {
  159. fprintf(stderr, "RSA_sign failed.\n");
  160. ERR_print_errors_fp(stderr);
  161. return false;
  162. }
  163. results.Print(name + " signing");
  164. if (!TimeFunction(&results,
  165. [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
  166. return RSA_verify(
  167. NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
  168. sig.get(), sig_len, key.get());
  169. })) {
  170. fprintf(stderr, "RSA_verify failed.\n");
  171. ERR_print_errors_fp(stderr);
  172. return false;
  173. }
  174. results.Print(name + " verify (same key)");
  175. if (!TimeFunction(&results,
  176. [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
  177. // Usually during RSA verification we have to parse an RSA key from a
  178. // certificate or similar, in which case we'd need to construct a new
  179. // RSA key, with a new |BN_MONT_CTX| for the public modulus. If we
  180. // were to use |key| directly instead, then these costs wouldn't be
  181. // accounted for.
  182. bssl::UniquePtr<RSA> verify_key(RSA_new());
  183. if (!verify_key) {
  184. return false;
  185. }
  186. verify_key->n = BN_dup(key->n);
  187. verify_key->e = BN_dup(key->e);
  188. if (!verify_key->n ||
  189. !verify_key->e) {
  190. return false;
  191. }
  192. return RSA_verify(NID_sha256, fake_sha256_hash,
  193. sizeof(fake_sha256_hash), sig.get(), sig_len,
  194. verify_key.get());
  195. })) {
  196. fprintf(stderr, "RSA_verify failed.\n");
  197. ERR_print_errors_fp(stderr);
  198. return false;
  199. }
  200. results.Print(name + " verify (fresh key)");
  201. }
  202. return true;
  203. }
  204. static bool SpeedRSAKeyGen(const std::string &selected) {
  205. // Don't run this by default because it's so slow.
  206. if (selected != "RSAKeyGen") {
  207. return true;
  208. }
  209. bssl::UniquePtr<BIGNUM> e(BN_new());
  210. if (!BN_set_word(e.get(), 65537)) {
  211. return false;
  212. }
  213. const std::vector<int> kSizes = {2048, 3072, 4096};
  214. for (int size : kSizes) {
  215. const uint64_t start = time_now();
  216. unsigned num_calls = 0;
  217. unsigned us;
  218. std::vector<unsigned> durations;
  219. for (;;) {
  220. bssl::UniquePtr<RSA> rsa(RSA_new());
  221. const uint64_t iteration_start = time_now();
  222. if (!RSA_generate_key_ex(rsa.get(), size, e.get(), nullptr)) {
  223. fprintf(stderr, "RSA_generate_key_ex failed.\n");
  224. ERR_print_errors_fp(stderr);
  225. return false;
  226. }
  227. const uint64_t iteration_end = time_now();
  228. num_calls++;
  229. durations.push_back(iteration_end - iteration_start);
  230. us = iteration_end - start;
  231. if (us > 30 * 1000000 /* 30 secs */) {
  232. break;
  233. }
  234. }
  235. std::sort(durations.begin(), durations.end());
  236. printf("Did %u RSA %d key-gen operations in %uus (%.1f ops/sec)\n",
  237. num_calls, size, us,
  238. (static_cast<double>(num_calls) / us) * 1000000);
  239. const size_t n = durations.size();
  240. assert(n > 0);
  241. unsigned median = n & 1 ? durations[n / 2]
  242. : (durations[n / 2 - 1] + durations[n / 2]) / 2;
  243. printf(" min: %uus, median: %uus, max: %uus\n", durations[0], median,
  244. durations[n - 1]);
  245. }
  246. return true;
  247. }
  248. static uint8_t *align(uint8_t *in, unsigned alignment) {
  249. return reinterpret_cast<uint8_t *>(
  250. (reinterpret_cast<uintptr_t>(in) + alignment) &
  251. ~static_cast<size_t>(alignment - 1));
  252. }
  253. static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
  254. size_t chunk_len, size_t ad_len,
  255. evp_aead_direction_t direction) {
  256. static const unsigned kAlignment = 16;
  257. bssl::ScopedEVP_AEAD_CTX ctx;
  258. const size_t key_len = EVP_AEAD_key_length(aead);
  259. const size_t nonce_len = EVP_AEAD_nonce_length(aead);
  260. const size_t overhead_len = EVP_AEAD_max_overhead(aead);
  261. std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
  262. OPENSSL_memset(key.get(), 0, key_len);
  263. std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
  264. OPENSSL_memset(nonce.get(), 0, nonce_len);
  265. std::unique_ptr<uint8_t[]> in_storage(new uint8_t[chunk_len + kAlignment]);
  266. // N.B. for EVP_AEAD_CTX_seal_scatter the input and output buffers may be the
  267. // same size. However, in the direction == evp_aead_open case we still use
  268. // non-scattering seal, hence we add overhead_len to the size of this buffer.
  269. std::unique_ptr<uint8_t[]> out_storage(
  270. new uint8_t[chunk_len + overhead_len + kAlignment]);
  271. std::unique_ptr<uint8_t[]> in2_storage(
  272. new uint8_t[chunk_len + overhead_len + kAlignment]);
  273. std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
  274. OPENSSL_memset(ad.get(), 0, ad_len);
  275. std::unique_ptr<uint8_t[]> tag_storage(
  276. new uint8_t[overhead_len + kAlignment]);
  277. uint8_t *const in = align(in_storage.get(), kAlignment);
  278. OPENSSL_memset(in, 0, chunk_len);
  279. uint8_t *const out = align(out_storage.get(), kAlignment);
  280. OPENSSL_memset(out, 0, chunk_len + overhead_len);
  281. uint8_t *const tag = align(tag_storage.get(), kAlignment);
  282. OPENSSL_memset(tag, 0, overhead_len);
  283. uint8_t *const in2 = align(in2_storage.get(), kAlignment);
  284. if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
  285. EVP_AEAD_DEFAULT_TAG_LENGTH,
  286. evp_aead_seal)) {
  287. fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
  288. ERR_print_errors_fp(stderr);
  289. return false;
  290. }
  291. TimeResults results;
  292. if (direction == evp_aead_seal) {
  293. if (!TimeFunction(&results,
  294. [chunk_len, nonce_len, ad_len, overhead_len, in, out, tag,
  295. &ctx, &nonce, &ad]() -> bool {
  296. size_t tag_len;
  297. return EVP_AEAD_CTX_seal_scatter(
  298. ctx.get(), out, tag, &tag_len, overhead_len,
  299. nonce.get(), nonce_len, in, chunk_len, nullptr, 0,
  300. ad.get(), ad_len);
  301. })) {
  302. fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
  303. ERR_print_errors_fp(stderr);
  304. return false;
  305. }
  306. } else {
  307. size_t out_len;
  308. EVP_AEAD_CTX_seal(ctx.get(), out, &out_len, chunk_len + overhead_len,
  309. nonce.get(), nonce_len, in, chunk_len, ad.get(), ad_len);
  310. ctx.Reset();
  311. if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
  312. EVP_AEAD_DEFAULT_TAG_LENGTH,
  313. evp_aead_open)) {
  314. fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
  315. ERR_print_errors_fp(stderr);
  316. return false;
  317. }
  318. if (!TimeFunction(&results,
  319. [chunk_len, overhead_len, nonce_len, ad_len, in2, out,
  320. out_len, &ctx, &nonce, &ad]() -> bool {
  321. size_t in2_len;
  322. // N.B. EVP_AEAD_CTX_open_gather is not implemented for
  323. // all AEADs.
  324. return EVP_AEAD_CTX_open(ctx.get(), in2, &in2_len,
  325. chunk_len + overhead_len,
  326. nonce.get(), nonce_len, out,
  327. out_len, ad.get(), ad_len);
  328. })) {
  329. fprintf(stderr, "EVP_AEAD_CTX_open failed.\n");
  330. ERR_print_errors_fp(stderr);
  331. return false;
  332. }
  333. }
  334. results.PrintWithBytes(
  335. name + (direction == evp_aead_seal ? " seal" : " open"), chunk_len);
  336. return true;
  337. }
  338. static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
  339. size_t ad_len, const std::string &selected) {
  340. if (!selected.empty() && name.find(selected) == std::string::npos) {
  341. return true;
  342. }
  343. return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len,
  344. evp_aead_seal) &&
  345. SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len,
  346. evp_aead_seal) &&
  347. SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len,
  348. evp_aead_seal);
  349. }
  350. static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name,
  351. size_t ad_len, const std::string &selected) {
  352. if (!selected.empty() && name.find(selected) == std::string::npos) {
  353. return true;
  354. }
  355. return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len,
  356. evp_aead_open) &&
  357. SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len,
  358. evp_aead_open) &&
  359. SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len,
  360. evp_aead_open);
  361. }
  362. static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
  363. size_t chunk_len) {
  364. bssl::ScopedEVP_MD_CTX ctx;
  365. uint8_t scratch[8192];
  366. if (chunk_len > sizeof(scratch)) {
  367. return false;
  368. }
  369. TimeResults results;
  370. if (!TimeFunction(&results, [&ctx, md, chunk_len, &scratch]() -> bool {
  371. uint8_t digest[EVP_MAX_MD_SIZE];
  372. unsigned int md_len;
  373. return EVP_DigestInit_ex(ctx.get(), md, NULL /* ENGINE */) &&
  374. EVP_DigestUpdate(ctx.get(), scratch, chunk_len) &&
  375. EVP_DigestFinal_ex(ctx.get(), digest, &md_len);
  376. })) {
  377. fprintf(stderr, "EVP_DigestInit_ex failed.\n");
  378. ERR_print_errors_fp(stderr);
  379. return false;
  380. }
  381. results.PrintWithBytes(name, chunk_len);
  382. return true;
  383. }
  384. static bool SpeedHash(const EVP_MD *md, const std::string &name,
  385. const std::string &selected) {
  386. if (!selected.empty() && name.find(selected) == std::string::npos) {
  387. return true;
  388. }
  389. return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
  390. SpeedHashChunk(md, name + " (256 bytes)", 256) &&
  391. SpeedHashChunk(md, name + " (8192 bytes)", 8192);
  392. }
  393. static bool SpeedRandomChunk(const std::string &name, size_t chunk_len) {
  394. uint8_t scratch[8192];
  395. if (chunk_len > sizeof(scratch)) {
  396. return false;
  397. }
  398. TimeResults results;
  399. if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool {
  400. RAND_bytes(scratch, chunk_len);
  401. return true;
  402. })) {
  403. return false;
  404. }
  405. results.PrintWithBytes(name, chunk_len);
  406. return true;
  407. }
  408. static bool SpeedRandom(const std::string &selected) {
  409. if (!selected.empty() && selected != "RNG") {
  410. return true;
  411. }
  412. return SpeedRandomChunk("RNG (16 bytes)", 16) &&
  413. SpeedRandomChunk("RNG (256 bytes)", 256) &&
  414. SpeedRandomChunk("RNG (8192 bytes)", 8192);
  415. }
  416. static bool SpeedECDHCurve(const std::string &name, int nid,
  417. const std::string &selected) {
  418. if (!selected.empty() && name.find(selected) == std::string::npos) {
  419. return true;
  420. }
  421. bssl::UniquePtr<EC_KEY> peer_key(EC_KEY_new_by_curve_name(nid));
  422. if (!peer_key ||
  423. !EC_KEY_generate_key(peer_key.get())) {
  424. return false;
  425. }
  426. size_t peer_value_len = EC_POINT_point2oct(
  427. EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
  428. POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
  429. if (peer_value_len == 0) {
  430. return false;
  431. }
  432. std::unique_ptr<uint8_t[]> peer_value(new uint8_t[peer_value_len]);
  433. peer_value_len = EC_POINT_point2oct(
  434. EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
  435. POINT_CONVERSION_UNCOMPRESSED, peer_value.get(), peer_value_len, nullptr);
  436. if (peer_value_len == 0) {
  437. return false;
  438. }
  439. TimeResults results;
  440. if (!TimeFunction(&results, [nid, peer_value_len, &peer_value]() -> bool {
  441. bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
  442. if (!key ||
  443. !EC_KEY_generate_key(key.get())) {
  444. return false;
  445. }
  446. const EC_GROUP *const group = EC_KEY_get0_group(key.get());
  447. bssl::UniquePtr<EC_POINT> point(EC_POINT_new(group));
  448. bssl::UniquePtr<EC_POINT> peer_point(EC_POINT_new(group));
  449. bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
  450. bssl::UniquePtr<BIGNUM> x(BN_new());
  451. bssl::UniquePtr<BIGNUM> y(BN_new());
  452. if (!point || !peer_point || !ctx || !x || !y ||
  453. !EC_POINT_oct2point(group, peer_point.get(), peer_value.get(),
  454. peer_value_len, ctx.get()) ||
  455. !EC_POINT_mul(group, point.get(), NULL, peer_point.get(),
  456. EC_KEY_get0_private_key(key.get()), ctx.get()) ||
  457. !EC_POINT_get_affine_coordinates_GFp(group, point.get(), x.get(),
  458. y.get(), ctx.get())) {
  459. return false;
  460. }
  461. return true;
  462. })) {
  463. return false;
  464. }
  465. results.Print(name);
  466. return true;
  467. }
  468. static bool SpeedECDSACurve(const std::string &name, int nid,
  469. const std::string &selected) {
  470. if (!selected.empty() && name.find(selected) == std::string::npos) {
  471. return true;
  472. }
  473. bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
  474. if (!key ||
  475. !EC_KEY_generate_key(key.get())) {
  476. return false;
  477. }
  478. uint8_t signature[256];
  479. if (ECDSA_size(key.get()) > sizeof(signature)) {
  480. return false;
  481. }
  482. uint8_t digest[20];
  483. OPENSSL_memset(digest, 42, sizeof(digest));
  484. unsigned sig_len;
  485. TimeResults results;
  486. if (!TimeFunction(&results, [&key, &signature, &digest, &sig_len]() -> bool {
  487. return ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len,
  488. key.get()) == 1;
  489. })) {
  490. return false;
  491. }
  492. results.Print(name + " signing");
  493. if (!TimeFunction(&results, [&key, &signature, &digest, sig_len]() -> bool {
  494. return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
  495. key.get()) == 1;
  496. })) {
  497. return false;
  498. }
  499. results.Print(name + " verify");
  500. return true;
  501. }
  502. static bool SpeedECDH(const std::string &selected) {
  503. return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
  504. SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
  505. SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
  506. SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
  507. }
  508. static bool SpeedECDSA(const std::string &selected) {
  509. return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
  510. SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
  511. SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
  512. SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
  513. }
  514. static bool Speed25519(const std::string &selected) {
  515. if (!selected.empty() && selected.find("25519") == std::string::npos) {
  516. return true;
  517. }
  518. TimeResults results;
  519. uint8_t public_key[32], private_key[64];
  520. if (!TimeFunction(&results, [&public_key, &private_key]() -> bool {
  521. ED25519_keypair(public_key, private_key);
  522. return true;
  523. })) {
  524. return false;
  525. }
  526. results.Print("Ed25519 key generation");
  527. static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
  528. uint8_t signature[64];
  529. if (!TimeFunction(&results, [&private_key, &signature]() -> bool {
  530. return ED25519_sign(signature, kMessage, sizeof(kMessage),
  531. private_key) == 1;
  532. })) {
  533. return false;
  534. }
  535. results.Print("Ed25519 signing");
  536. if (!TimeFunction(&results, [&public_key, &signature]() -> bool {
  537. return ED25519_verify(kMessage, sizeof(kMessage), signature,
  538. public_key) == 1;
  539. })) {
  540. fprintf(stderr, "Ed25519 verify failed.\n");
  541. return false;
  542. }
  543. results.Print("Ed25519 verify");
  544. if (!TimeFunction(&results, []() -> bool {
  545. uint8_t out[32], in[32];
  546. OPENSSL_memset(in, 0, sizeof(in));
  547. X25519_public_from_private(out, in);
  548. return true;
  549. })) {
  550. fprintf(stderr, "Curve25519 base-point multiplication failed.\n");
  551. return false;
  552. }
  553. results.Print("Curve25519 base-point multiplication");
  554. if (!TimeFunction(&results, []() -> bool {
  555. uint8_t out[32], in1[32], in2[32];
  556. OPENSSL_memset(in1, 0, sizeof(in1));
  557. OPENSSL_memset(in2, 0, sizeof(in2));
  558. in1[0] = 1;
  559. in2[0] = 9;
  560. return X25519(out, in1, in2) == 1;
  561. })) {
  562. fprintf(stderr, "Curve25519 arbitrary point multiplication failed.\n");
  563. return false;
  564. }
  565. results.Print("Curve25519 arbitrary point multiplication");
  566. return true;
  567. }
  568. static bool SpeedSPAKE2(const std::string &selected) {
  569. if (!selected.empty() && selected.find("SPAKE2") == std::string::npos) {
  570. return true;
  571. }
  572. TimeResults results;
  573. static const uint8_t kAliceName[] = {'A'};
  574. static const uint8_t kBobName[] = {'B'};
  575. static const uint8_t kPassword[] = "password";
  576. bssl::UniquePtr<SPAKE2_CTX> alice(SPAKE2_CTX_new(spake2_role_alice,
  577. kAliceName, sizeof(kAliceName), kBobName,
  578. sizeof(kBobName)));
  579. uint8_t alice_msg[SPAKE2_MAX_MSG_SIZE];
  580. size_t alice_msg_len;
  581. if (!SPAKE2_generate_msg(alice.get(), alice_msg, &alice_msg_len,
  582. sizeof(alice_msg),
  583. kPassword, sizeof(kPassword))) {
  584. fprintf(stderr, "SPAKE2_generate_msg failed.\n");
  585. return false;
  586. }
  587. if (!TimeFunction(&results, [&alice_msg, alice_msg_len]() -> bool {
  588. bssl::UniquePtr<SPAKE2_CTX> bob(SPAKE2_CTX_new(spake2_role_bob,
  589. kBobName, sizeof(kBobName), kAliceName,
  590. sizeof(kAliceName)));
  591. uint8_t bob_msg[SPAKE2_MAX_MSG_SIZE], bob_key[64];
  592. size_t bob_msg_len, bob_key_len;
  593. if (!SPAKE2_generate_msg(bob.get(), bob_msg, &bob_msg_len,
  594. sizeof(bob_msg), kPassword,
  595. sizeof(kPassword)) ||
  596. !SPAKE2_process_msg(bob.get(), bob_key, &bob_key_len,
  597. sizeof(bob_key), alice_msg, alice_msg_len)) {
  598. return false;
  599. }
  600. return true;
  601. })) {
  602. fprintf(stderr, "SPAKE2 failed.\n");
  603. }
  604. results.Print("SPAKE2 over Ed25519");
  605. return true;
  606. }
  607. static bool SpeedScrypt(const std::string &selected) {
  608. if (!selected.empty() && selected.find("scrypt") == std::string::npos) {
  609. return true;
  610. }
  611. TimeResults results;
  612. static const char kPassword[] = "password";
  613. static const uint8_t kSalt[] = "NaCl";
  614. if (!TimeFunction(&results, [&]() -> bool {
  615. uint8_t out[64];
  616. return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
  617. sizeof(kSalt) - 1, 1024, 8, 16, 0 /* max_mem */,
  618. out, sizeof(out));
  619. })) {
  620. fprintf(stderr, "scrypt failed.\n");
  621. return false;
  622. }
  623. results.Print("scrypt (N = 1024, r = 8, p = 16)");
  624. if (!TimeFunction(&results, [&]() -> bool {
  625. uint8_t out[64];
  626. return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
  627. sizeof(kSalt) - 1, 16384, 8, 1, 0 /* max_mem */,
  628. out, sizeof(out));
  629. })) {
  630. fprintf(stderr, "scrypt failed.\n");
  631. return false;
  632. }
  633. results.Print("scrypt (N = 16384, r = 8, p = 1)");
  634. return true;
  635. }
  636. static const struct argument kArguments[] = {
  637. {
  638. "-filter", kOptionalArgument,
  639. "A filter on the speed tests to run",
  640. },
  641. {
  642. "-timeout", kOptionalArgument,
  643. "The number of seconds to run each test for (default is 1)",
  644. },
  645. {
  646. "", kOptionalArgument, "",
  647. },
  648. };
  649. bool Speed(const std::vector<std::string> &args) {
  650. std::map<std::string, std::string> args_map;
  651. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  652. PrintUsage(kArguments);
  653. return false;
  654. }
  655. std::string selected;
  656. if (args_map.count("-filter") != 0) {
  657. selected = args_map["-filter"];
  658. }
  659. if (args_map.count("-timeout") != 0) {
  660. g_timeout_seconds = atoi(args_map["-timeout"].c_str());
  661. }
  662. // kTLSADLen is the number of bytes of additional data that TLS passes to
  663. // AEADs.
  664. static const size_t kTLSADLen = 13;
  665. // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
  666. // These are AEADs that weren't originally defined as AEADs, but which we use
  667. // via the AEAD interface. In order for that to work, they have some TLS
  668. // knowledge in them and construct a couple of the AD bytes internally.
  669. static const size_t kLegacyADLen = kTLSADLen - 2;
  670. if (!SpeedRSA(selected) ||
  671. !SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
  672. !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
  673. !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
  674. selected) ||
  675. !SpeedAEAD(EVP_aead_des_ede3_cbc_sha1_tls(), "DES-EDE3-CBC-SHA1",
  676. kLegacyADLen, selected) ||
  677. !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
  678. kLegacyADLen, selected) ||
  679. !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
  680. kLegacyADLen, selected) ||
  681. !SpeedAEADOpen(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
  682. kLegacyADLen, selected) ||
  683. !SpeedAEADOpen(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
  684. kLegacyADLen, selected) ||
  685. !SpeedAEAD(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
  686. selected) ||
  687. !SpeedAEAD(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
  688. selected) ||
  689. !SpeedAEADOpen(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
  690. selected) ||
  691. !SpeedAEADOpen(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
  692. selected) ||
  693. !SpeedAEAD(EVP_aead_aes_128_ccm_bluetooth(), "AES-128-CCM-Bluetooth",
  694. kTLSADLen, selected) ||
  695. !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
  696. !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
  697. !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
  698. !SpeedRandom(selected) ||
  699. !SpeedECDH(selected) ||
  700. !SpeedECDSA(selected) ||
  701. !Speed25519(selected) ||
  702. !SpeedSPAKE2(selected) ||
  703. !SpeedScrypt(selected) ||
  704. !SpeedRSAKeyGen(selected)) {
  705. return false;
  706. }
  707. return true;
  708. }