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