• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
PrintTimeResults58   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 
PrintWithBytesTimeResults64   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)
time_now()73 static uint64_t time_now() { return GetTickCount64() * 1000; }
74 #elif defined(OPENSSL_APPLE)
time_now()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
time_now()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 
TimeFunction(TimeResults * results,std::function<bool ()> func)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 
SpeedRSA(const std::string & key_name,RSA * key,const std::string & selected)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 
align(uint8_t * in,unsigned alignment)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 
SpeedAEADChunk(const EVP_AEAD * aead,const std::string & name,size_t chunk_len,size_t ad_len,evp_aead_direction_t direction)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   std::unique_ptr<uint8_t[]> out_storage(new uint8_t[chunk_len + overhead_len + kAlignment]);
219   std::unique_ptr<uint8_t[]> in2_storage(new uint8_t[chunk_len + kAlignment]);
220   std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
221   OPENSSL_memset(ad.get(), 0, ad_len);
222 
223   uint8_t *const in = align(in_storage.get(), kAlignment);
224   OPENSSL_memset(in, 0, chunk_len);
225   uint8_t *const out = align(out_storage.get(), kAlignment);
226   OPENSSL_memset(out, 0, chunk_len + overhead_len);
227   uint8_t *const in2 = align(in2_storage.get(), kAlignment);
228 
229   if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
230                                         EVP_AEAD_DEFAULT_TAG_LENGTH,
231                                         evp_aead_seal)) {
232     fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
233     ERR_print_errors_fp(stderr);
234     return false;
235   }
236 
237   TimeResults results;
238   if (direction == evp_aead_seal) {
239     if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, in,
240                                  out, &ctx, &nonce, &ad]() -> bool {
241           size_t out_len;
242           return EVP_AEAD_CTX_seal(ctx.get(), out, &out_len,
243                                    chunk_len + overhead_len, nonce.get(),
244                                    nonce_len, in, chunk_len, ad.get(), ad_len);
245         })) {
246       fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
247       ERR_print_errors_fp(stderr);
248       return false;
249     }
250   } else {
251     size_t out_len;
252     EVP_AEAD_CTX_seal(ctx.get(), out, &out_len, chunk_len + overhead_len,
253                       nonce.get(), nonce_len, in, chunk_len, ad.get(), ad_len);
254 
255     if (!TimeFunction(&results, [chunk_len, nonce_len, ad_len, in2, out, &ctx,
256                                  &nonce, &ad, out_len]() -> bool {
257           size_t in2_len;
258           return EVP_AEAD_CTX_open(ctx.get(), in2, &in2_len, chunk_len,
259                                    nonce.get(), nonce_len, out, out_len,
260                                    ad.get(), ad_len);
261         })) {
262       fprintf(stderr, "EVP_AEAD_CTX_open failed.\n");
263       ERR_print_errors_fp(stderr);
264       return false;
265     }
266   }
267 
268   results.PrintWithBytes(
269       name + (direction == evp_aead_seal ? " seal" : " open"), chunk_len);
270   return true;
271 }
272 
SpeedAEAD(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)273 static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
274                       size_t ad_len, const std::string &selected) {
275   if (!selected.empty() && name.find(selected) == std::string::npos) {
276     return true;
277   }
278 
279   return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len,
280                         evp_aead_seal) &&
281          SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len,
282                         evp_aead_seal) &&
283          SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len,
284                         evp_aead_seal);
285 }
286 
SpeedAEADOpen(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)287 static bool SpeedAEADOpen(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_open) &&
295          SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len,
296                         evp_aead_open) &&
297          SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len,
298                         evp_aead_open);
299 }
300 
SpeedHashChunk(const EVP_MD * md,const std::string & name,size_t chunk_len)301 static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
302                            size_t chunk_len) {
303   EVP_MD_CTX *ctx = EVP_MD_CTX_create();
304   uint8_t scratch[8192];
305 
306   if (chunk_len > sizeof(scratch)) {
307     return false;
308   }
309 
310   TimeResults results;
311   if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
312         uint8_t digest[EVP_MAX_MD_SIZE];
313         unsigned int md_len;
314 
315         return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
316                EVP_DigestUpdate(ctx, scratch, chunk_len) &&
317                EVP_DigestFinal_ex(ctx, digest, &md_len);
318       })) {
319     fprintf(stderr, "EVP_DigestInit_ex failed.\n");
320     ERR_print_errors_fp(stderr);
321     return false;
322   }
323 
324   results.PrintWithBytes(name, chunk_len);
325 
326   EVP_MD_CTX_destroy(ctx);
327 
328   return true;
329 }
SpeedHash(const EVP_MD * md,const std::string & name,const std::string & selected)330 static bool SpeedHash(const EVP_MD *md, const std::string &name,
331                       const std::string &selected) {
332   if (!selected.empty() && name.find(selected) == std::string::npos) {
333     return true;
334   }
335 
336   return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
337          SpeedHashChunk(md, name + " (256 bytes)", 256) &&
338          SpeedHashChunk(md, name + " (8192 bytes)", 8192);
339 }
340 
SpeedRandomChunk(const std::string & name,size_t chunk_len)341 static bool SpeedRandomChunk(const std::string &name, size_t chunk_len) {
342   uint8_t scratch[8192];
343 
344   if (chunk_len > sizeof(scratch)) {
345     return false;
346   }
347 
348   TimeResults results;
349   if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool {
350         RAND_bytes(scratch, chunk_len);
351         return true;
352       })) {
353     return false;
354   }
355 
356   results.PrintWithBytes(name, chunk_len);
357   return true;
358 }
359 
SpeedRandom(const std::string & selected)360 static bool SpeedRandom(const std::string &selected) {
361   if (!selected.empty() && selected != "RNG") {
362     return true;
363   }
364 
365   return SpeedRandomChunk("RNG (16 bytes)", 16) &&
366          SpeedRandomChunk("RNG (256 bytes)", 256) &&
367          SpeedRandomChunk("RNG (8192 bytes)", 8192);
368 }
369 
SpeedECDHCurve(const std::string & name,int nid,const std::string & selected)370 static bool SpeedECDHCurve(const std::string &name, int nid,
371                            const std::string &selected) {
372   if (!selected.empty() && name.find(selected) == std::string::npos) {
373     return true;
374   }
375 
376   TimeResults results;
377   if (!TimeFunction(&results, [nid]() -> bool {
378         bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
379         if (!key ||
380             !EC_KEY_generate_key(key.get())) {
381           return false;
382         }
383         const EC_GROUP *const group = EC_KEY_get0_group(key.get());
384         bssl::UniquePtr<EC_POINT> point(EC_POINT_new(group));
385         bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
386 
387         bssl::UniquePtr<BIGNUM> x(BN_new());
388         bssl::UniquePtr<BIGNUM> y(BN_new());
389 
390         if (!point || !ctx || !x || !y ||
391             !EC_POINT_mul(group, point.get(), NULL,
392                           EC_KEY_get0_public_key(key.get()),
393                           EC_KEY_get0_private_key(key.get()), ctx.get()) ||
394             !EC_POINT_get_affine_coordinates_GFp(group, point.get(), x.get(),
395                                                  y.get(), ctx.get())) {
396           return false;
397         }
398 
399         return true;
400       })) {
401     return false;
402   }
403 
404   results.Print(name);
405   return true;
406 }
407 
SpeedECDSACurve(const std::string & name,int nid,const std::string & selected)408 static bool SpeedECDSACurve(const std::string &name, int nid,
409                             const std::string &selected) {
410   if (!selected.empty() && name.find(selected) == std::string::npos) {
411     return true;
412   }
413 
414   bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
415   if (!key ||
416       !EC_KEY_generate_key(key.get())) {
417     return false;
418   }
419 
420   uint8_t signature[256];
421   if (ECDSA_size(key.get()) > sizeof(signature)) {
422     return false;
423   }
424   uint8_t digest[20];
425   OPENSSL_memset(digest, 42, sizeof(digest));
426   unsigned sig_len;
427 
428   TimeResults results;
429   if (!TimeFunction(&results, [&key, &signature, &digest, &sig_len]() -> bool {
430         return ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len,
431                           key.get()) == 1;
432       })) {
433     return false;
434   }
435 
436   results.Print(name + " signing");
437 
438   if (!TimeFunction(&results, [&key, &signature, &digest, sig_len]() -> bool {
439         return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
440                             key.get()) == 1;
441       })) {
442     return false;
443   }
444 
445   results.Print(name + " verify");
446 
447   return true;
448 }
449 
SpeedECDH(const std::string & selected)450 static bool SpeedECDH(const std::string &selected) {
451   return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
452          SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
453          SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
454          SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
455 }
456 
SpeedECDSA(const std::string & selected)457 static bool SpeedECDSA(const std::string &selected) {
458   return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
459          SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
460          SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
461          SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
462 }
463 
Speed25519(const std::string & selected)464 static bool Speed25519(const std::string &selected) {
465   if (!selected.empty() && selected.find("25519") == std::string::npos) {
466     return true;
467   }
468 
469   TimeResults results;
470 
471   uint8_t public_key[32], private_key[64];
472 
473   if (!TimeFunction(&results, [&public_key, &private_key]() -> bool {
474         ED25519_keypair(public_key, private_key);
475         return true;
476       })) {
477     return false;
478   }
479 
480   results.Print("Ed25519 key generation");
481 
482   static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
483   uint8_t signature[64];
484 
485   if (!TimeFunction(&results, [&private_key, &signature]() -> bool {
486         return ED25519_sign(signature, kMessage, sizeof(kMessage),
487                             private_key) == 1;
488       })) {
489     return false;
490   }
491 
492   results.Print("Ed25519 signing");
493 
494   if (!TimeFunction(&results, [&public_key, &signature]() -> bool {
495         return ED25519_verify(kMessage, sizeof(kMessage), signature,
496                               public_key) == 1;
497       })) {
498     fprintf(stderr, "Ed25519 verify failed.\n");
499     return false;
500   }
501 
502   results.Print("Ed25519 verify");
503 
504   if (!TimeFunction(&results, []() -> bool {
505         uint8_t out[32], in[32];
506         OPENSSL_memset(in, 0, sizeof(in));
507         X25519_public_from_private(out, in);
508         return true;
509       })) {
510     fprintf(stderr, "Curve25519 base-point multiplication failed.\n");
511     return false;
512   }
513 
514   results.Print("Curve25519 base-point multiplication");
515 
516   if (!TimeFunction(&results, []() -> bool {
517         uint8_t out[32], in1[32], in2[32];
518         OPENSSL_memset(in1, 0, sizeof(in1));
519         OPENSSL_memset(in2, 0, sizeof(in2));
520         in1[0] = 1;
521         in2[0] = 9;
522         return X25519(out, in1, in2) == 1;
523       })) {
524     fprintf(stderr, "Curve25519 arbitrary point multiplication failed.\n");
525     return false;
526   }
527 
528   results.Print("Curve25519 arbitrary point multiplication");
529 
530   return true;
531 }
532 
SpeedSPAKE2(const std::string & selected)533 static bool SpeedSPAKE2(const std::string &selected) {
534   if (!selected.empty() && selected.find("SPAKE2") == std::string::npos) {
535     return true;
536   }
537 
538   TimeResults results;
539 
540   static const uint8_t kAliceName[] = {'A'};
541   static const uint8_t kBobName[] = {'B'};
542   static const uint8_t kPassword[] = "password";
543   bssl::UniquePtr<SPAKE2_CTX> alice(SPAKE2_CTX_new(spake2_role_alice,
544                                     kAliceName, sizeof(kAliceName), kBobName,
545                                     sizeof(kBobName)));
546   uint8_t alice_msg[SPAKE2_MAX_MSG_SIZE];
547   size_t alice_msg_len;
548 
549   if (!SPAKE2_generate_msg(alice.get(), alice_msg, &alice_msg_len,
550                            sizeof(alice_msg),
551                            kPassword, sizeof(kPassword))) {
552     fprintf(stderr, "SPAKE2_generate_msg failed.\n");
553     return false;
554   }
555 
556   if (!TimeFunction(&results, [&alice_msg, alice_msg_len]() -> bool {
557         bssl::UniquePtr<SPAKE2_CTX> bob(SPAKE2_CTX_new(spake2_role_bob,
558                                         kBobName, sizeof(kBobName), kAliceName,
559                                         sizeof(kAliceName)));
560         uint8_t bob_msg[SPAKE2_MAX_MSG_SIZE], bob_key[64];
561         size_t bob_msg_len, bob_key_len;
562         if (!SPAKE2_generate_msg(bob.get(), bob_msg, &bob_msg_len,
563                                  sizeof(bob_msg), kPassword,
564                                  sizeof(kPassword)) ||
565             !SPAKE2_process_msg(bob.get(), bob_key, &bob_key_len,
566                                 sizeof(bob_key), alice_msg, alice_msg_len)) {
567           return false;
568         }
569 
570         return true;
571       })) {
572     fprintf(stderr, "SPAKE2 failed.\n");
573   }
574 
575   results.Print("SPAKE2 over Ed25519");
576 
577   return true;
578 }
579 
SpeedScrypt(const std::string & selected)580 static bool SpeedScrypt(const std::string &selected) {
581   if (!selected.empty() && selected.find("scrypt") == std::string::npos) {
582     return true;
583   }
584 
585   TimeResults results;
586 
587   static const char kPassword[] = "password";
588   static const uint8_t kSalt[] = "NaCl";
589 
590   if (!TimeFunction(&results, [&]() -> bool {
591         uint8_t out[64];
592         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
593                                 sizeof(kSalt) - 1, 1024, 8, 16, 0 /* max_mem */,
594                                 out, sizeof(out));
595       })) {
596     fprintf(stderr, "scrypt failed.\n");
597     return false;
598   }
599   results.Print("scrypt (N = 1024, r = 8, p = 16)");
600 
601   if (!TimeFunction(&results, [&]() -> bool {
602         uint8_t out[64];
603         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
604                                 sizeof(kSalt) - 1, 16384, 8, 1, 0 /* max_mem */,
605                                 out, sizeof(out));
606       })) {
607     fprintf(stderr, "scrypt failed.\n");
608     return false;
609   }
610   results.Print("scrypt (N = 16384, r = 8, p = 1)");
611 
612   return true;
613 }
614 
615 static const struct argument kArguments[] = {
616     {
617      "-filter", kOptionalArgument,
618      "A filter on the speed tests to run",
619     },
620     {
621      "-timeout", kOptionalArgument,
622      "The number of seconds to run each test for (default is 1)",
623     },
624     {
625      "", kOptionalArgument, "",
626     },
627 };
628 
Speed(const std::vector<std::string> & args)629 bool Speed(const std::vector<std::string> &args) {
630   std::map<std::string, std::string> args_map;
631   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
632     PrintUsage(kArguments);
633     return false;
634   }
635 
636   std::string selected;
637   if (args_map.count("-filter") != 0) {
638     selected = args_map["-filter"];
639   }
640 
641   if (args_map.count("-timeout") != 0) {
642     g_timeout_seconds = atoi(args_map["-timeout"].c_str());
643   }
644 
645   bssl::UniquePtr<RSA> key(
646       RSA_private_key_from_bytes(kDERRSAPrivate2048, kDERRSAPrivate2048Len));
647   if (key == nullptr) {
648     fprintf(stderr, "Failed to parse RSA key.\n");
649     ERR_print_errors_fp(stderr);
650     return false;
651   }
652 
653   if (!SpeedRSA("RSA 2048", key.get(), selected)) {
654     return false;
655   }
656 
657   key.reset(
658       RSA_private_key_from_bytes(kDERRSAPrivate4096, kDERRSAPrivate4096Len));
659   if (key == nullptr) {
660     fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
661     ERR_print_errors_fp(stderr);
662     return 1;
663   }
664 
665   if (!SpeedRSA("RSA 4096", key.get(), selected)) {
666     return false;
667   }
668 
669   key.reset();
670 
671   // kTLSADLen is the number of bytes of additional data that TLS passes to
672   // AEADs.
673   static const size_t kTLSADLen = 13;
674   // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
675   // These are AEADs that weren't originally defined as AEADs, but which we use
676   // via the AEAD interface. In order for that to work, they have some TLS
677   // knowledge in them and construct a couple of the AD bytes internally.
678   static const size_t kLegacyADLen = kTLSADLen - 2;
679 
680   if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
681       !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
682       !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
683                  selected) ||
684       !SpeedAEAD(EVP_aead_des_ede3_cbc_sha1_tls(), "DES-EDE3-CBC-SHA1",
685                  kLegacyADLen, selected) ||
686       !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
687                  kLegacyADLen, selected) ||
688       !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
689                  kLegacyADLen, selected) ||
690       !SpeedAEAD(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
691                  selected) ||
692       !SpeedAEAD(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
693                  selected) ||
694       !SpeedAEADOpen(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
695                      selected) ||
696       !SpeedAEADOpen(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
697                      selected) ||
698       !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
699       !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
700       !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
701       !SpeedRandom(selected) ||
702       !SpeedECDH(selected) ||
703       !SpeedECDSA(selected) ||
704       !Speed25519(selected) ||
705       !SpeedSPAKE2(selected) ||
706       !SpeedScrypt(selected)) {
707     return false;
708   }
709 
710   return true;
711 }
712