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

452 lines
15 KiB

  1. /**
  2. * @file test_decaf.cxx
  3. * @author Mike Hamburg
  4. *
  5. * @copyright
  6. * Copyright (c) 2015 Cryptography Research, Inc. \n
  7. * Released under the MIT License. See LICENSE.txt for license information.
  8. *
  9. * @brief C++ benchmarks, because that's easier.
  10. */
  11. #include <decaf.hxx>
  12. #include <decaf/shake.hxx>
  13. #include <decaf/sha512.hxx>
  14. #include <decaf/strobe.hxx>
  15. #include <decaf/spongerng.hxx>
  16. #include <decaf/crypto_255.h>
  17. #include <decaf/crypto_448.h>
  18. #include <decaf/crypto.hxx>
  19. #include <decaf/eddsa.hxx>
  20. #include <stdio.h>
  21. #include <sys/time.h>
  22. #include <assert.h>
  23. #include <stdint.h>
  24. #include <vector>
  25. #include <algorithm>
  26. using namespace decaf;
  27. static __inline__ void __attribute__((unused)) ignore_result ( int result ) { (void)result; }
  28. static double now(void) {
  29. struct timeval tv;
  30. gettimeofday(&tv, NULL);
  31. return tv.tv_sec + tv.tv_usec/1000000.0;
  32. }
  33. // RDTSC from the chacha code
  34. #ifndef __has_builtin
  35. #define __has_builtin(X) 0
  36. #endif
  37. #if defined(__clang__) && __has_builtin(__builtin_readcyclecounter)
  38. #define rdtsc __builtin_readcyclecounter
  39. #else
  40. static inline uint64_t rdtsc(void) {
  41. u_int64_t out = 0;
  42. # if (defined(__i386__) || defined(__x86_64__))
  43. __asm__ __volatile__ ("rdtsc" : "=A"(out));
  44. # endif
  45. return out;
  46. }
  47. #endif
  48. static void printSI(double x, const char *unit, const char *spacer = " ") {
  49. const char *small[] = {" ","m","ยต","n","p"};
  50. const char *big[] = {" ","k","M","G","T"};
  51. if (x < 1) {
  52. unsigned di=0;
  53. for (di=0; di<sizeof(small)/sizeof(*small)-1 && x && x < 1; di++) {
  54. x *= 1000.0;
  55. }
  56. printf("%6.2f%s%s%s", x, spacer, small[di], unit);
  57. } else {
  58. unsigned di=0;
  59. for (di=0; di<sizeof(big)/sizeof(*big)-1 && x && x >= 1000; di++) {
  60. x /= 1000.0;
  61. }
  62. printf("%6.2f%s%s%s", x, spacer, big[di], unit);
  63. }
  64. }
  65. class Benchmark {
  66. static const int NTESTS = 20, NSAMPLES=50, DISCARD=2;
  67. static double totalCy, totalS;
  68. public:
  69. int i, j, ntests, nsamples;
  70. double begin;
  71. uint64_t tsc_begin;
  72. std::vector<double> times;
  73. std::vector<uint64_t> cycles;
  74. Benchmark(const char *s, double factor = 1) {
  75. printf("%s:", s);
  76. if (strlen(s) < 25) printf("%*s",int(25-strlen(s)),"");
  77. fflush(stdout);
  78. i = j = 0;
  79. ntests = NTESTS * factor;
  80. nsamples = NSAMPLES;
  81. begin = now();
  82. tsc_begin = rdtsc();
  83. times = std::vector<double>(NSAMPLES);
  84. cycles = std::vector<uint64_t>(NSAMPLES);
  85. }
  86. ~Benchmark() {
  87. double tsc = 0;
  88. double t = 0;
  89. std::sort(times.begin(), times.end());
  90. std::sort(cycles.begin(), cycles.end());
  91. for (int k=DISCARD; k<nsamples-DISCARD; k++) {
  92. tsc += cycles[k];
  93. t += times[k];
  94. }
  95. totalCy += tsc;
  96. totalS += t;
  97. t /= ntests*(nsamples-2*DISCARD);
  98. tsc /= ntests*(nsamples-2*DISCARD);
  99. printSI(t,"s");
  100. printf(" ");
  101. printSI(1/t,"/s");
  102. if (tsc) { printf(" "); printSI(tsc, "cy"); }
  103. printf("\n");
  104. }
  105. inline bool iter() {
  106. i++;
  107. if (i >= ntests) {
  108. uint64_t tsc = rdtsc() - tsc_begin;
  109. double t = now() - begin;
  110. begin += t;
  111. tsc_begin += tsc;
  112. assert(j >= 0 && j < nsamples);
  113. cycles[j] = tsc;
  114. times[j] = t;
  115. j++;
  116. i = 0;
  117. }
  118. return j < nsamples;
  119. }
  120. static void calib() {
  121. if (totalS && totalCy) {
  122. const char *s = "Cycle calibration";
  123. printf("%s:", s);
  124. if (strlen(s) < 25) printf("%*s",int(25-strlen(s)),"");
  125. printSI(totalCy / totalS, "Hz");
  126. printf("\n");
  127. }
  128. }
  129. };
  130. double Benchmark::totalCy = 0, Benchmark::totalS = 0;
  131. template<typename Group> struct Benches {
  132. typedef typename Group::Scalar Scalar;
  133. typedef typename Group::Point Point;
  134. typedef typename Group::Precomputed Precomputed;
  135. static void tdh (
  136. SpongeRng &clientRng,
  137. SpongeRng &serverRng,
  138. Scalar x, const Block &gx,
  139. Scalar y, const Block &gy
  140. ) {
  141. /* "TripleDH". A bit of a hack, really: the real TripleDH
  142. * sends gx and gy and certs over the channel, but its goal
  143. * is actually the opposite of STROBE in this case: it doesn't
  144. * hash gx and gy into the session secret (only into the MAC
  145. * and AD) because of IPR concerns.
  146. */
  147. Strobe client("example::tripleDH",Strobe::CLIENT), server("example::tripleDH",Strobe::SERVER);
  148. Scalar xe(clientRng);
  149. SecureBuffer gxe((Precomputed::base() * xe).serialize());
  150. client.send_plaintext(gxe);
  151. server.recv_plaintext(gxe);
  152. Scalar ye(serverRng);
  153. SecureBuffer gye((Precomputed::base() * ye).serialize());
  154. server.send_plaintext(gye);
  155. client.recv_plaintext(gye);
  156. Point pgxe(gxe);
  157. server.dh_key(pgxe*ye);
  158. SecureBuffer tag1 = server.produce_auth();
  159. //SecureBuffer ct = server.encrypt(gy);
  160. server.dh_key(pgxe*y);
  161. SecureBuffer tag2 = server.produce_auth();
  162. Point pgye(gye);
  163. client.dh_key(pgye*xe);
  164. client.verify_auth(tag1);
  165. client.dh_key(Point(gy) * xe);
  166. client.verify_auth(tag2);
  167. // ct = client.encrypt(gx);
  168. client.dh_key(pgye * x);
  169. tag1 = client.produce_auth();
  170. client.respec(STROBE_KEYED_128);
  171. server.dh_key(Point(gx) * ye);
  172. server.verify_auth(tag1);
  173. server.respec(STROBE_KEYED_128);
  174. }
  175. static void fhmqv (
  176. SpongeRng &clientRng,
  177. SpongeRng &serverRng,
  178. Scalar x, const Block &gx,
  179. Scalar y, const Block &gy
  180. ) {
  181. /* Don't use this, it's probably patented */
  182. Strobe client("example::fhmqv",Strobe::CLIENT), server("example::fhmqv",Strobe::SERVER);
  183. Scalar xe(clientRng);
  184. client.send_plaintext(gx);
  185. server.recv_plaintext(gx);
  186. SecureBuffer gxe((Precomputed::base() * xe).serialize());
  187. server.send_plaintext(gxe);
  188. client.recv_plaintext(gxe);
  189. Scalar ye(serverRng);
  190. server.send_plaintext(gy);
  191. client.recv_plaintext(gy);
  192. SecureBuffer gye((Precomputed::base() * ye).serialize());
  193. server.send_plaintext(gye);
  194. Scalar schx(server.prng(Scalar::SER_BYTES));
  195. Scalar schy(server.prng(Scalar::SER_BYTES));
  196. Scalar yec = y + ye*schy;
  197. server.dh_key(Point::double_scalarmul(Point(gx),yec,Point(gxe),yec*schx));
  198. SecureBuffer as = server.produce_auth();
  199. client.recv_plaintext(gye);
  200. Scalar cchx(client.prng(Scalar::SER_BYTES));
  201. Scalar cchy(client.prng(Scalar::SER_BYTES));
  202. Scalar xec = x + xe*schx;
  203. client.dh_key(Point::double_scalarmul(Point(gy),xec,Point(gye),xec*schy));
  204. client.verify_auth(as);
  205. SecureBuffer ac = client.produce_auth();
  206. client.respec(STROBE_KEYED_128);
  207. server.verify_auth(ac);
  208. server.respec(STROBE_KEYED_128);
  209. }
  210. static void spake2ee(
  211. SpongeRng &clientRng,
  212. SpongeRng &serverRng,
  213. const Block &hashed_password,
  214. bool aug
  215. ) {
  216. Strobe client("example::spake2ee",Strobe::CLIENT), server("example::spake2ee",Strobe::SERVER);
  217. Scalar x(clientRng);
  218. SHAKE<256> shake;
  219. shake.update(hashed_password);
  220. SecureBuffer h0 = shake.output(Point::HASH_BYTES);
  221. SecureBuffer h1 = shake.output(Point::HASH_BYTES);
  222. SecureBuffer h2 = shake.output(Scalar::SER_BYTES);
  223. Scalar gs(h2);
  224. Point hc = Point::from_hash(h0);
  225. hc = Point::from_hash(h0); // double-count
  226. Point hs = Point::from_hash(h1);
  227. hs = Point::from_hash(h1); // double-count
  228. SecureBuffer gx((Precomputed::base() * x + hc).serialize());
  229. client.send_plaintext(gx);
  230. server.recv_plaintext(gx);
  231. Scalar y(serverRng);
  232. SecureBuffer gy((Precomputed::base() * y + hs).serialize());
  233. server.send_plaintext(gy);
  234. client.recv_plaintext(gy);
  235. server.dh_key(h1);
  236. server.dh_key((Point(gx) - hc)*y);
  237. if(aug) {
  238. /* This step isn't actually online but whatever, it's fastish */
  239. SecureBuffer serverAug((Precomputed::base() * gs).serialize());
  240. server.dh_key(Point(serverAug)*y);
  241. }
  242. SecureBuffer tag = server.produce_auth();
  243. client.dh_key(h1);
  244. Point pgy(gy); pgy -= hs;
  245. client.dh_key(pgy*x);
  246. if (aug) client.dh_key(pgy * gs);
  247. client.verify_auth(tag);
  248. tag = client.produce_auth();
  249. client.respec(STROBE_KEYED_128);
  250. /* A real protocol would continue with fork etc here... */
  251. server.verify_auth(tag);
  252. server.respec(STROBE_KEYED_128);
  253. }
  254. static void cfrg() {
  255. SpongeRng rng(Block("bench_cfrg_crypto"),SpongeRng::DETERMINISTIC);
  256. FixedArrayBuffer<Group::DhLadder::PUBLIC_BYTES> base(rng);
  257. FixedArrayBuffer<Group::DhLadder::PRIVATE_BYTES> s1(rng);
  258. for (Benchmark b("RFC 7748 keygen"); b.iter(); ) { Group::DhLadder::generate_key(s1); }
  259. for (Benchmark b("RFC 7748 shared secret"); b.iter(); ) { Group::DhLadder::shared_secret(base,s1); }
  260. FixedArrayBuffer<EdDSA<Group>::PrivateKey::SER_BYTES> e1(rng);
  261. typename EdDSA<Group>::PublicKey pub((NOINIT()));
  262. typename EdDSA<Group>::PrivateKey priv((NOINIT()));
  263. SecureBuffer sig;
  264. for (Benchmark b("EdDSA keygen"); b.iter(); ) { priv = e1; }
  265. for (Benchmark b("EdDSA sign"); b.iter(); ) { sig = priv.sign(Block(NULL,0)); }
  266. pub = priv;
  267. for (Benchmark b("EdDSA verify"); b.iter(); ) { pub.verify(sig,Block(NULL,0)); }
  268. }
  269. static void macro() {
  270. printf("\nMacro-benchmarks for %s:\n", Group::name());
  271. printf("CFRG crypto benchmarks:\n");
  272. cfrg();
  273. printf("\nSample crypto benchmarks:\n");
  274. SpongeRng rng(Block("macro rng seed"),SpongeRng::DETERMINISTIC);
  275. PrivateKey<Group> s1((NOINIT())), s2(rng);
  276. PublicKey<Group> p1((NOINIT())), p2(s2);
  277. SecureBuffer message = rng.read(5), sig, ss;
  278. for (Benchmark b("Create private key",1); b.iter(); ) {
  279. s1 = PrivateKey<Group>(rng);
  280. SecureBuffer bb = s1.serialize();
  281. }
  282. for (Benchmark b("Sign",1); b.iter(); ) {
  283. sig = s1.sign(message);
  284. }
  285. p1 = s1.pub();
  286. for (Benchmark b("Verify",1); b.iter(); ) {
  287. rng.read(Buffer(message));
  288. try { p1.verify(message, sig); } catch (CryptoException) {}
  289. }
  290. for (Benchmark b("SharedSecret",1); b.iter(); ) {
  291. ss = s1.shared_secret(p2,32,true);
  292. }
  293. printf("\nProtocol benchmarks:\n");
  294. SpongeRng clientRng(Block("client rng seed"),SpongeRng::DETERMINISTIC);
  295. SpongeRng serverRng(Block("server rng seed"),SpongeRng::DETERMINISTIC);
  296. SecureBuffer hashedPassword(Block("hello world"));
  297. for (Benchmark b("Spake2ee c+s",0.1); b.iter(); ) {
  298. spake2ee(clientRng, serverRng, hashedPassword,false);
  299. }
  300. for (Benchmark b("Spake2ee c+s aug",0.1); b.iter(); ) {
  301. spake2ee(clientRng, serverRng, hashedPassword,true);
  302. }
  303. Scalar x(clientRng);
  304. SecureBuffer gx((Precomputed::base() * x).serialize());
  305. Scalar y(serverRng);
  306. SecureBuffer gy((Precomputed::base() * y).serialize());
  307. for (Benchmark b("FHMQV c+s",0.1); b.iter(); ) {
  308. fhmqv(clientRng, serverRng,x,gx,y,gy);
  309. }
  310. for (Benchmark b("TripleDH anon c+s",0.1); b.iter(); ) {
  311. tdh(clientRng, serverRng, x,gx,y,gy);
  312. }
  313. }
  314. static void micro() {
  315. SpongeRng rng(Block("per-curve-benchmarks"),SpongeRng::DETERMINISTIC);
  316. Precomputed pBase;
  317. Point p,q;
  318. Scalar s(1),t(2);
  319. SecureBuffer ep, ep2(Point::SER_BYTES*2);
  320. printf("\nMicro-benchmarks for %s:\n", Group::name());
  321. for (Benchmark b("Scalar add", 1000); b.iter(); ) { s+=t; }
  322. for (Benchmark b("Scalar times", 100); b.iter(); ) { s*=t; }
  323. for (Benchmark b("Scalar inv", 1); b.iter(); ) { s.inverse(); }
  324. for (Benchmark b("Point add", 100); b.iter(); ) { p += q; }
  325. for (Benchmark b("Point double", 100); b.iter(); ) { p.double_in_place(); }
  326. for (Benchmark b("Point scalarmul"); b.iter(); ) { p * s; }
  327. for (Benchmark b("Point encode"); b.iter(); ) { ep = p.serialize(); }
  328. for (Benchmark b("Point decode"); b.iter(); ) { p = Point(ep); }
  329. for (Benchmark b("Point create/destroy"); b.iter(); ) { Point r; }
  330. for (Benchmark b("Point hash nonuniform"); b.iter(); ) { Point::from_hash(ep); }
  331. for (Benchmark b("Point hash uniform"); b.iter(); ) { Point::from_hash(ep2); }
  332. for (Benchmark b("Point unhash nonuniform"); b.iter(); ) { ignore_result(p.invert_elligator(ep,0)); }
  333. for (Benchmark b("Point unhash uniform"); b.iter(); ) { ignore_result(p.invert_elligator(ep2,0)); }
  334. for (Benchmark b("Point steg"); b.iter(); ) { p.steg_encode(rng); }
  335. for (Benchmark b("Point double scalarmul"); b.iter(); ) { Point::double_scalarmul(p,s,q,t); }
  336. for (Benchmark b("Point dual scalarmul"); b.iter(); ) { p.dual_scalarmul(p,q,s,t); }
  337. for (Benchmark b("Point precmp scalarmul"); b.iter(); ) { pBase * s; }
  338. for (Benchmark b("Point double scalarmul_v"); b.iter(); ) {
  339. s = Scalar(rng);
  340. t = Scalar(rng);
  341. p.non_secret_combo_with_base(s,t);
  342. }
  343. }
  344. }; /* template <typename group> struct Benches */
  345. template <typename Group> struct Macro { static void run() { Benches<Group>::macro(); } };
  346. template <typename Group> struct Micro { static void run() { Benches<Group>::micro(); } };
  347. int main(int argc, char **argv) {
  348. bool micro = false;
  349. if (argc >= 2 && !strcmp(argv[1], "--micro"))
  350. micro = true;
  351. SpongeRng rng(Block("micro-benchmarks"),SpongeRng::DETERMINISTIC);
  352. if (micro) {
  353. printf("\nMicro-benchmarks:\n");
  354. SHAKE<128> shake1;
  355. SHAKE<256> shake2;
  356. SHA3<512> sha5;
  357. SHA512 sha2;
  358. Strobe strobe("example::bench",Strobe::CLIENT);
  359. unsigned char b1024[1024] = {1};
  360. for (Benchmark b("SHAKE128 1kiB", 30); b.iter(); ) { shake1 += Buffer(b1024,1024); }
  361. for (Benchmark b("SHAKE256 1kiB", 30); b.iter(); ) { shake2 += Buffer(b1024,1024); }
  362. for (Benchmark b("SHA3-512 1kiB", 30); b.iter(); ) { sha5 += Buffer(b1024,1024); }
  363. for (Benchmark b("SHA512 1kiB", 30); b.iter(); ) { sha2 += Buffer(b1024,1024); }
  364. strobe.dh_key(Buffer(b1024,1024));
  365. strobe.respec(STROBE_128);
  366. for (Benchmark b("STROBE128 1kiB", 10); b.iter(); ) {
  367. strobe.encrypt_no_auth(Buffer(b1024,1024),Buffer(b1024,1024));
  368. }
  369. strobe.respec(STROBE_256);
  370. for (Benchmark b("STROBE256 1kiB", 10); b.iter(); ) {
  371. strobe.encrypt_no_auth(Buffer(b1024,1024),Buffer(b1024,1024));
  372. }
  373. strobe.respec(STROBE_KEYED_128);
  374. for (Benchmark b("STROBEk128 1kiB", 10); b.iter(); ) {
  375. strobe.encrypt_no_auth(Buffer(b1024,1024),Buffer(b1024,1024));
  376. }
  377. strobe.respec(STROBE_KEYED_256);
  378. for (Benchmark b("STROBEk256 1kiB", 10); b.iter(); ) {
  379. strobe.encrypt_no_auth(Buffer(b1024,1024),Buffer(b1024,1024));
  380. }
  381. run_for_all_curves<Micro>();
  382. }
  383. run_for_all_curves<Macro>();
  384. printf("\n");
  385. Benchmark::calib();
  386. printf("\n");
  387. return 0;
  388. }