25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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