Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

293 linhas
8.5 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 <string>
  15. #include <functional>
  16. #include <memory>
  17. #include <vector>
  18. #include <stdint.h>
  19. #include <time.h>
  20. #include <openssl/aead.h>
  21. #include <openssl/bio.h>
  22. #include <openssl/digest.h>
  23. #include <openssl/obj.h>
  24. #include <openssl/rsa.h>
  25. #if defined(OPENSSL_WINDOWS)
  26. #include <Windows.h>
  27. #elif defined(OPENSSL_APPLE)
  28. #include <sys/time.h>
  29. #endif
  30. extern "C" {
  31. // These values are DER encoded, RSA private keys.
  32. extern const uint8_t kDERRSAPrivate2048[];
  33. extern size_t kDERRSAPrivate2048Len;
  34. extern const uint8_t kDERRSAPrivate4096[];
  35. extern size_t kDERRSAPrivate4096Len;
  36. }
  37. // TimeResults represents the results of benchmarking a function.
  38. struct TimeResults {
  39. // num_calls is the number of function calls done in the time period.
  40. unsigned num_calls;
  41. // us is the number of microseconds that elapsed in the time period.
  42. unsigned us;
  43. void Print(const std::string &description) {
  44. printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
  45. description.c_str(), us,
  46. (static_cast<double>(num_calls) / us) * 1000000);
  47. }
  48. void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
  49. printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
  50. num_calls, description.c_str(), us,
  51. (static_cast<double>(num_calls) / us) * 1000000,
  52. static_cast<double>(bytes_per_call * num_calls) / us);
  53. }
  54. };
  55. #if defined(OPENSSL_WINDOWS)
  56. static uint64_t time_now() { return GetTickCount64() * 1000; }
  57. #elif defined(OPENSSL_APPLE)
  58. static uint64_t time_now() {
  59. struct timeval tv;
  60. uint64_t ret;
  61. gettimeofday(&tv, NULL);
  62. ret = tv.tv_sec;
  63. ret *= 1000000;
  64. ret += tv.tv_usec;
  65. return ret;
  66. }
  67. #else
  68. static uint64_t time_now() {
  69. struct timespec ts;
  70. clock_gettime(CLOCK_MONOTONIC, &ts);
  71. uint64_t ret = ts.tv_sec;
  72. ret *= 1000000;
  73. ret += ts.tv_nsec / 1000;
  74. return ret;
  75. }
  76. #endif
  77. static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
  78. // kTotalMS is the total amount of time that we'll aim to measure a function
  79. // for.
  80. static const uint64_t kTotalUS = 3000000;
  81. uint64_t start = time_now(), now, delta;
  82. unsigned done = 0, iterations_between_time_checks;
  83. if (!func()) {
  84. return false;
  85. }
  86. now = time_now();
  87. delta = now - start;
  88. if (delta == 0) {
  89. iterations_between_time_checks = 250;
  90. } else {
  91. // Aim for about 100ms between time checks.
  92. iterations_between_time_checks =
  93. static_cast<double>(100000) / static_cast<double>(delta);
  94. if (iterations_between_time_checks > 1000) {
  95. iterations_between_time_checks = 1000;
  96. } else if (iterations_between_time_checks < 1) {
  97. iterations_between_time_checks = 1;
  98. }
  99. }
  100. for (;;) {
  101. for (unsigned i = 0; i < iterations_between_time_checks; i++) {
  102. if (!func()) {
  103. return false;
  104. }
  105. done++;
  106. }
  107. now = time_now();
  108. if (now - start > kTotalUS) {
  109. break;
  110. }
  111. }
  112. results->us = now - start;
  113. results->num_calls = done;
  114. return true;
  115. }
  116. static bool SpeedRSA(const std::string& key_name, RSA *key) {
  117. TimeResults results;
  118. std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
  119. const uint8_t fake_sha256_hash[32] = {0};
  120. unsigned sig_len;
  121. if (!TimeFunction(&results,
  122. [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
  123. return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
  124. sig.get(), &sig_len, key);
  125. })) {
  126. fprintf(stderr, "RSA_sign failed.\n");
  127. BIO_print_errors_fp(stderr);
  128. return false;
  129. }
  130. results.Print(key_name + " signing");
  131. if (!TimeFunction(&results,
  132. [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
  133. return RSA_verify(NID_sha256, fake_sha256_hash,
  134. sizeof(fake_sha256_hash), sig.get(), sig_len, key);
  135. })) {
  136. fprintf(stderr, "RSA_verify failed.\n");
  137. BIO_print_errors_fp(stderr);
  138. return false;
  139. }
  140. results.Print(key_name + " verify");
  141. return true;
  142. }
  143. static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
  144. size_t chunk_len) {
  145. EVP_AEAD_CTX ctx;
  146. const size_t key_len = EVP_AEAD_key_length(aead);
  147. const size_t nonce_len = EVP_AEAD_nonce_length(aead);
  148. const size_t overhead_len = EVP_AEAD_max_overhead(aead);
  149. std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
  150. memset(key.get(), 0, key_len);
  151. std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
  152. memset(nonce.get(), 0, nonce_len);
  153. std::unique_ptr<uint8_t[]> in(new uint8_t[chunk_len]);
  154. memset(in.get(), 0, chunk_len);
  155. std::unique_ptr<uint8_t[]> out(new uint8_t[chunk_len + overhead_len]);
  156. memset(out.get(), 0, chunk_len + overhead_len);
  157. if (!EVP_AEAD_CTX_init(&ctx, aead, key.get(), key_len,
  158. EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) {
  159. fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
  160. BIO_print_errors_fp(stderr);
  161. return false;
  162. }
  163. TimeResults results;
  164. if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, &in, &out,
  165. &ctx, &nonce]() -> bool {
  166. size_t out_len;
  167. return EVP_AEAD_CTX_seal(&ctx, out.get(), &out_len,
  168. chunk_len + overhead_len, nonce.get(),
  169. nonce_len, in.get(), chunk_len, NULL, 0);
  170. })) {
  171. fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
  172. BIO_print_errors_fp(stderr);
  173. return false;
  174. }
  175. results.PrintWithBytes(name + " seal", chunk_len);
  176. EVP_AEAD_CTX_cleanup(&ctx);
  177. return true;
  178. }
  179. static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name) {
  180. return SpeedAEADChunk(aead, name + " (16 bytes)", 16) &&
  181. SpeedAEADChunk(aead, name + " (1350 bytes)", 1350) &&
  182. SpeedAEADChunk(aead, name + " (8192 bytes)", 8192);
  183. }
  184. static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
  185. size_t chunk_len) {
  186. EVP_MD_CTX *ctx = EVP_MD_CTX_create();
  187. uint8_t scratch[8192];
  188. if (chunk_len > sizeof(scratch)) {
  189. return false;
  190. }
  191. TimeResults results;
  192. if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
  193. uint8_t digest[EVP_MAX_MD_SIZE];
  194. unsigned int md_len;
  195. return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
  196. EVP_DigestUpdate(ctx, scratch, chunk_len) &&
  197. EVP_DigestFinal_ex(ctx, digest, &md_len);
  198. })) {
  199. fprintf(stderr, "EVP_DigestInit_ex failed.\n");
  200. BIO_print_errors_fp(stderr);
  201. return false;
  202. }
  203. results.PrintWithBytes(name, chunk_len);
  204. EVP_MD_CTX_destroy(ctx);
  205. return true;
  206. }
  207. static bool SpeedHash(const EVP_MD *md, const std::string &name) {
  208. return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
  209. SpeedHashChunk(md, name + " (256 bytes)", 256) &&
  210. SpeedHashChunk(md, name + " (8192 bytes)", 8192);
  211. }
  212. bool Speed(const std::vector<std::string> &args) {
  213. const uint8_t *inp;
  214. RSA *key = NULL;
  215. inp = kDERRSAPrivate2048;
  216. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
  217. fprintf(stderr, "Failed to parse RSA key.\n");
  218. BIO_print_errors_fp(stderr);
  219. return false;
  220. }
  221. if (!SpeedRSA("RSA 2048", key)) {
  222. return false;
  223. }
  224. RSA_free(key);
  225. key = NULL;
  226. inp = kDERRSAPrivate4096;
  227. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
  228. fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
  229. BIO_print_errors_fp(stderr);
  230. return 1;
  231. }
  232. if (!SpeedRSA("RSA 4096", key)) {
  233. return false;
  234. }
  235. RSA_free(key);
  236. if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM") ||
  237. !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM") ||
  238. !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305") ||
  239. !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5") ||
  240. !SpeedHash(EVP_sha1(), "SHA-1") ||
  241. !SpeedHash(EVP_sha256(), "SHA-256") ||
  242. !SpeedHash(EVP_sha512(), "SHA-512")) {
  243. return false;
  244. }
  245. return 0;
  246. }