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.
 
 
 
 
 

594 lines
19 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++ tests, because that's easier.
  10. */
  11. #include <decaf.hxx>
  12. #include <decaf/spongerng.hxx>
  13. #include <decaf/crypto.h>
  14. #include <decaf/crypto.hxx>
  15. #include <decaf/eddsa.hxx>
  16. #include <stdio.h>
  17. using namespace decaf;
  18. static bool passing = true;
  19. static const long NTESTS = 10000;
  20. class Test {
  21. public:
  22. bool passing_now;
  23. Test(const char *test) {
  24. passing_now = true;
  25. printf("%s...", test);
  26. if (strlen(test) < 27) printf("%*s",int(27-strlen(test)),"");
  27. fflush(stdout);
  28. }
  29. ~Test() {
  30. if (std::uncaught_exception()) {
  31. fail();
  32. printf(" due to uncaught exception.\n");
  33. }
  34. if (passing_now) printf("[PASS]\n");
  35. }
  36. void fail() {
  37. if (!passing_now) return;
  38. passing_now = passing = false;
  39. printf("[FAIL]\n");
  40. }
  41. };
  42. static uint64_t leint(const SecureBuffer &xx) {
  43. uint64_t out = 0;
  44. for (unsigned int i=0; i<xx.size() && i<sizeof(out); i++) {
  45. out |= uint64_t(xx[i]) << (8*i);
  46. }
  47. return out;
  48. }
  49. template<typename Group> struct Tests {
  50. typedef typename Group::Scalar Scalar;
  51. typedef typename Group::Point Point;
  52. typedef typename Group::DhLadder DhLadder;
  53. typedef typename Group::Precomputed Precomputed;
  54. static void print(const char *name, const Scalar &x) {
  55. unsigned char buffer[Scalar::SER_BYTES];
  56. x.serialize_into(buffer);
  57. printf(" %s = 0x", name);
  58. for (int i=sizeof(buffer)-1; i>=0; i--) {
  59. printf("%02x", buffer[i]);
  60. }
  61. printf("\n");
  62. }
  63. static void hexprint(const char *name, const SecureBuffer &buffer) {
  64. printf(" %s = 0x", name);
  65. for (int i=buffer.size()-1; i>=0; i--) {
  66. printf("%02x", buffer[i]);
  67. }
  68. printf("\n");
  69. }
  70. static void print(const char *name, const Point &x) {
  71. unsigned char buffer[Point::SER_BYTES];
  72. x.serialize_into(buffer);
  73. printf(" %s = 0x", name);
  74. for (int i=Point::SER_BYTES-1; i>=0; i--) {
  75. printf("%02x", buffer[i]);
  76. }
  77. printf("\n");
  78. }
  79. static bool arith_check(
  80. Test &test,
  81. const Scalar &x,
  82. const Scalar &y,
  83. const Scalar &z,
  84. const Scalar &l,
  85. const Scalar &r,
  86. const char *name
  87. ) {
  88. if (l == r) return true;
  89. test.fail();
  90. printf(" %s", name);
  91. print("x", x);
  92. print("y", y);
  93. print("z", z);
  94. print("lhs", l);
  95. print("rhs", r);
  96. return false;
  97. }
  98. static bool point_check(
  99. Test &test,
  100. const Point &p,
  101. const Point &q,
  102. const Point &R,
  103. const Scalar &x,
  104. const Scalar &y,
  105. const Point &l,
  106. const Point &r,
  107. const char *name
  108. ) {
  109. bool good = l==r;
  110. if (!p.validate()) { good = false; printf(" p invalid\n"); }
  111. if (!q.validate()) { good = false; printf(" q invalid\n"); }
  112. if (!r.validate()) { good = false; printf(" r invalid\n"); }
  113. if (!l.validate()) { good = false; printf(" l invalid\n"); }
  114. if (good) return true;
  115. test.fail();
  116. printf(" %s", name);
  117. print("x", x);
  118. print("y", y);
  119. print("p", p);
  120. print("q", q);
  121. print("r", R);
  122. print("lhs", r);
  123. print("rhs", l);
  124. return false;
  125. }
  126. static void test_arithmetic() {
  127. SpongeRng rng(Block("test_arithmetic"),SpongeRng::DETERMINISTIC);
  128. Test test("Arithmetic");
  129. Scalar x(0),y(0),z(0);
  130. arith_check(test,x,y,z,INT_MAX,(decaf_word_t)INT_MAX,"cast from max");
  131. arith_check(test,x,y,z,INT_MIN,-Scalar(1+(decaf_word_t)INT_MAX),"cast from min");
  132. for (int i=0; i<NTESTS*10 && test.passing_now; i++) {
  133. size_t sob = i % (2*Group::Scalar::SER_BYTES);
  134. SecureBuffer xx = rng.read(sob), yy = rng.read(sob), zz = rng.read(sob);
  135. Scalar x(xx);
  136. Scalar y(yy);
  137. Scalar z(zz);
  138. arith_check(test,x,y,z,x+y,y+x,"commute add");
  139. arith_check(test,x,y,z,x,x+0,"ident add");
  140. arith_check(test,x,y,z,x,x-0,"ident sub");
  141. arith_check(test,x,y,z,x+-x,0,"inverse add");
  142. arith_check(test,x,y,z,x-x,0,"inverse sub");
  143. arith_check(test,x,y,z,x-(x+1),-1,"inverse add2");
  144. arith_check(test,x,y,z,x+(y+z),(x+y)+z,"assoc add");
  145. arith_check(test,x,y,z,x*(y+z),x*y + x*z,"distributive mul/add");
  146. arith_check(test,x,y,z,x*(y-z),x*y - x*z,"distributive mul/add");
  147. arith_check(test,x,y,z,x*(y*z),(x*y)*z,"assoc mul");
  148. arith_check(test,x,y,z,x*y,y*x,"commute mul");
  149. arith_check(test,x,y,z,x,x*1,"ident mul");
  150. arith_check(test,x,y,z,0,x*0,"mul by 0");
  151. arith_check(test,x,y,z,-x,x*-1,"mul by -1");
  152. arith_check(test,x,y,z,x+x,x*2,"mul by 2");
  153. arith_check(test,x,y,z,-(x*y),(-x)*y,"neg prop mul");
  154. arith_check(test,x,y,z,x*y,(-x)*(-y),"double neg prop mul");
  155. arith_check(test,x,y,z,-(x+y),(-x)+(-y),"neg prop add");
  156. arith_check(test,x,y,z,x-y,(x)+(-y),"add neg sub");
  157. arith_check(test,x,y,z,(-x)-y,-(x+y),"neg add");
  158. if (sob <= 4) {
  159. uint64_t xi = leint(xx), yi = leint(yy);
  160. arith_check(test,x,y,z,x,xi,"parse consistency");
  161. arith_check(test,x,y,z,x+y,xi+yi,"add consistency");
  162. arith_check(test,x,y,z,x*y,xi*yi,"mul consistency");
  163. }
  164. if (i%20) continue;
  165. if (y!=0) arith_check(test,x,y,z,x*y/y,x,"invert");
  166. try {
  167. y = x/0;
  168. test.fail();
  169. printf(" Inverted zero!");
  170. print("x", x);
  171. print("y", y);
  172. } catch(CryptoException) {}
  173. }
  174. }
  175. static const Block sqrt_minus_one;
  176. static const Block minus_sqrt_minus_one;
  177. static const Block elli_patho; /* sqrt(1/(u(1-d))) */
  178. static void test_elligator() {
  179. SpongeRng rng(Block("test_elligator"),SpongeRng::DETERMINISTIC);
  180. Test test("Elligator");
  181. const int NHINTS = 1<<Point::INVERT_ELLIGATOR_WHICH_BITS;
  182. SecureBuffer *alts[NHINTS];
  183. bool successes[NHINTS];
  184. SecureBuffer *alts2[NHINTS];
  185. bool successes2[NHINTS];
  186. for (int i=0; i<NTESTS/10 && (i<10 || test.passing_now); i++) {
  187. size_t len = (i % (2*Point::HASH_BYTES + 3));
  188. SecureBuffer b1(len);
  189. if (i!=Point::HASH_BYTES) rng.read(b1); /* special test case */
  190. /* Pathological cases */
  191. if (i==1) b1[0] = 1;
  192. if (i==2 && sqrt_minus_one.size()) b1 = sqrt_minus_one;
  193. if (i==3 && minus_sqrt_minus_one.size()) b1 = minus_sqrt_minus_one;
  194. if (i==4 && elli_patho.size()) b1 = elli_patho;
  195. len = b1.size();
  196. Point s = Point::from_hash(b1), ss=s;
  197. for (int j=0; j<(i&3); j++) ss = ss.debugging_torque();
  198. ss = ss.debugging_pscale(rng);
  199. bool good = false;
  200. for (int j=0; j<NHINTS; j++) {
  201. alts[j] = new SecureBuffer(len);
  202. alts2[j] = new SecureBuffer(len);
  203. if (len > Point::HASH_BYTES)
  204. memcpy(&(*alts[j])[Point::HASH_BYTES], &b1[Point::HASH_BYTES], len-Point::HASH_BYTES);
  205. if (len > Point::HASH_BYTES)
  206. memcpy(&(*alts2[j])[Point::HASH_BYTES], &b1[Point::HASH_BYTES], len-Point::HASH_BYTES);
  207. successes[j] = decaf_successful( s.invert_elligator(*alts[j], j));
  208. successes2[j] = decaf_successful(ss.invert_elligator(*alts2[j],j));
  209. if (successes[j] != successes2[j]
  210. || (successes[j] && successes2[j] && *alts[j] != *alts2[j])
  211. ) {
  212. test.fail();
  213. printf(" Unscalable Elligator inversion: i=%d, hint=%d, s=%d,%d\n",i,j,
  214. -int(successes[j]),-int(successes2[j]));
  215. hexprint("x",b1);
  216. hexprint("X",*alts[j]);
  217. hexprint("X",*alts2[j]);
  218. }
  219. if (successes[j]) {
  220. good = good || (b1 == *alts[j]);
  221. for (int k=0; k<j; k++) {
  222. if (successes[k] && *alts[j] == *alts[k]) {
  223. test.fail();
  224. printf(" Duplicate Elligator inversion: i=%d, hints=%d, %d\n",i,j,k);
  225. hexprint("x",b1);
  226. hexprint("X",*alts[j]);
  227. }
  228. }
  229. if (s != Point::from_hash(*alts[j])) {
  230. test.fail();
  231. printf(" Fail Elligator inversion round-trip: i=%d, hint=%d %s\n",i,j,
  232. (s==-Point::from_hash(*alts[j])) ? "[output was -input]": "");
  233. hexprint("x",b1);
  234. hexprint("X",*alts[j]);
  235. }
  236. }
  237. }
  238. if (!good) {
  239. test.fail();
  240. printf(" %s Elligator inversion: i=%d\n",good ? "Passed" : "Failed", i);
  241. hexprint("B", b1);
  242. for (int j=0; j<NHINTS; j++) {
  243. printf(" %d: %s%s", j, successes[j] ? "succ" : "fail\n", (successes[j] && *alts[j] == b1) ? " [x]" : "");
  244. if (successes[j]) {
  245. hexprint("b", *alts[j]);
  246. }
  247. }
  248. printf("\n");
  249. }
  250. for (int j=0; j<NHINTS; j++) {
  251. delete alts[j];
  252. alts[j] = NULL;
  253. delete alts2[j];
  254. alts2[j] = NULL;
  255. }
  256. Point t(rng);
  257. point_check(test,t,t,t,0,0,t,Point::from_hash(t.steg_encode(rng)),"steg round-trip");
  258. }
  259. }
  260. static void test_ec() {
  261. SpongeRng rng(Block("test_ec"),SpongeRng::DETERMINISTIC);
  262. Test test("EC");
  263. Point id = Point::identity(), base = Point::base();
  264. point_check(test,id,id,id,0,0,Point::from_hash(""),id,"fh0");
  265. unsigned char enc[Point::SER_BYTES] = {0};
  266. if (Group::FIELD_MODULUS_TYPE == 3) {
  267. /* When p == 3 mod 4, the QNR is -1, so u*1^2 = -1 also produces the
  268. * identity.
  269. */
  270. point_check(test,id,id,id,0,0,Point::from_hash("\x01"),id,"fh1");
  271. }
  272. point_check(test,id,id,id,0,0,Point(FixedBlock<sizeof(enc)>(enc)),id,"decode [0]");
  273. try {
  274. enc[0] = 1;
  275. Point f((FixedBlock<sizeof(enc)>(enc)));
  276. test.fail();
  277. printf(" Allowed deserialize of [1]: %d", f==id);
  278. } catch (CryptoException) {
  279. /* ok */
  280. }
  281. if (sqrt_minus_one.size()) {
  282. try {
  283. Point f(sqrt_minus_one);
  284. test.fail();
  285. printf(" Allowed deserialize of [i]: %d", f==id);
  286. } catch (CryptoException) {
  287. /* ok */
  288. }
  289. }
  290. if (minus_sqrt_minus_one.size()) {
  291. try {
  292. Point f(minus_sqrt_minus_one);
  293. test.fail();
  294. printf(" Allowed deserialize of [-i]: %d", f==id);
  295. } catch (CryptoException) {
  296. /* ok */
  297. }
  298. }
  299. for (int i=0; i<NTESTS && test.passing_now; i++) {
  300. Scalar x(rng);
  301. Scalar y(rng);
  302. Point p(rng);
  303. Point q(rng);
  304. Point d1, d2;
  305. SecureBuffer buffer(2*Point::HASH_BYTES);
  306. rng.read(buffer);
  307. Point r = Point::from_hash(buffer);
  308. point_check(test,p,q,r,0,0,p,Point(p.serialize()),"round-trip");
  309. Point pp = p.debugging_torque().debugging_pscale(rng);
  310. if (!memeq(pp.serialize(),p.serialize())) {
  311. test.fail();
  312. printf(" Fail torque seq test\n");
  313. }
  314. if (!memeq((p-pp).serialize(),id.serialize())) {
  315. test.fail();
  316. printf(" Fail torque id test\n");
  317. }
  318. if (!memeq((p-p).serialize(),id.serialize())) {
  319. test.fail();
  320. printf(" Fail id test\n");
  321. }
  322. point_check(test,p,q,r,0,0,p,pp,"torque eq");
  323. point_check(test,p,q,r,0,0,p+q,q+p,"commute add");
  324. point_check(test,p,q,r,0,0,(p-q)+q,p,"correct sub");
  325. point_check(test,p,q,r,0,0,p+(q+r),(p+q)+r,"assoc add");
  326. point_check(test,p,q,r,0,0,p.times_two(),p+p,"dbl add");
  327. if (i%10) continue;
  328. point_check(test,p,q,r,0,0,p.times_two(),p*Scalar(2),"add times two");
  329. point_check(test,p,q,r,x,0,x*(p+q),x*p+x*q,"distr mul");
  330. point_check(test,p,q,r,x,y,(x*y)*p,x*(y*p),"assoc mul");
  331. point_check(test,p,q,r,x,y,x*p+y*q,Point::double_scalarmul(x,p,y,q),"double mul");
  332. p.dual_scalarmul(d1,d2,x,y);
  333. point_check(test,p,q,r,x,y,x*p,d1,"dual mul 1");
  334. point_check(test,p,q,r,x,y,y*p,d2,"dual mul 2");
  335. point_check(test,base,q,r,x,y,x*base+y*q,q.non_secret_combo_with_base(y,x),"ds vt mul");
  336. point_check(test,p,q,r,x,0,Precomputed(p)*x,p*x,"precomp mul");
  337. point_check(test,p,q,r,0,0,r,
  338. Point::from_hash(Buffer(buffer).slice(0,Point::HASH_BYTES))
  339. + Point::from_hash(Buffer(buffer).slice(Point::HASH_BYTES,Point::HASH_BYTES)),
  340. "unih = hash+add"
  341. );
  342. point_check(test,p,q,r,x,0,Point(x.direct_scalarmul(p.serialize())),x*p,"direct mul");
  343. q=p;
  344. for (int j=1; j<Group::REMOVED_COFACTOR; j<<=1) q = q.times_two();
  345. decaf_error_t error = r.decode_like_eddsa_noexcept(p.encode_like_eddsa());
  346. if (error != DECAF_SUCCESS) {
  347. test.fail();
  348. printf(" Decode like EdDSA failed.");
  349. }
  350. point_check(test,-q,q,r,i,0,q,r,"Encode like EdDSA round-trip");
  351. }
  352. }
  353. static void test_crypto() {
  354. Test test("Sample crypto");
  355. SpongeRng rng(Block("test_decaf_crypto"),SpongeRng::DETERMINISTIC);
  356. for (int i=0; i<NTESTS && test.passing_now; i++) {
  357. try {
  358. PrivateKey<Group> priv1(rng), priv2(rng);
  359. PublicKey<Group> pub1(priv1), pub2(priv2);
  360. SecureBuffer message = rng.read(i);
  361. SecureBuffer sig(priv1.sign(message));
  362. pub1.verify(message, sig);
  363. SecureBuffer s1(priv1.shared_secret(pub2,32,true));
  364. SecureBuffer s2(priv2.shared_secret(pub1,32,false));
  365. if (!memeq(s1,s2)) {
  366. test.fail();
  367. printf(" Shared secrets disagree on iteration %d.\n",i);
  368. }
  369. } catch (CryptoException) {
  370. test.fail();
  371. printf(" Threw CryptoException.\n");
  372. }
  373. }
  374. }
  375. static const uint8_t rfc7748_1[DhLadder::PUBLIC_BYTES];
  376. static const uint8_t rfc7748_1000[DhLadder::PUBLIC_BYTES];
  377. static const uint8_t rfc7748_1000000[DhLadder::PUBLIC_BYTES];
  378. static void test_cfrg_crypto() {
  379. Test test("CFRG crypto");
  380. SpongeRng rng(Block("test_cfrg_crypto"),SpongeRng::DETERMINISTIC);
  381. for (int i=0; i<NTESTS && test.passing_now; i++) {
  382. FixedArrayBuffer<DhLadder::PUBLIC_BYTES> base(rng);
  383. FixedArrayBuffer<DhLadder::PRIVATE_BYTES> s1(rng), s2(rng);
  384. SecureBuffer p1 = DhLadder::shared_secret(base,s1);
  385. SecureBuffer p2 = DhLadder::shared_secret(base,s2);
  386. SecureBuffer ss1 = DhLadder::shared_secret(p2,s1);
  387. SecureBuffer ss2 = DhLadder::shared_secret(p1,s2);
  388. if (!memeq(ss1,ss2)) {
  389. test.fail();
  390. printf(" Shared secrets disagree on iteration %d.\n",i);
  391. }
  392. if (!memeq(
  393. DhLadder::shared_secret(DhLadder::base_point(),s1),
  394. DhLadder::generate_key(s1)
  395. )) {
  396. test.fail();
  397. printf(" Generated keys disagree on iteration %d.\n",i);
  398. }
  399. }
  400. }
  401. static const bool eddsa_prehashed[];
  402. static const Block eddsa_sk[], eddsa_pk[], eddsa_message[], eddsa_context[], eddsa_sig[];
  403. static void test_cfrg_vectors() {
  404. Test test("CFRG test vectors");
  405. SecureBuffer k = DhLadder::base_point();
  406. SecureBuffer u = DhLadder::base_point();
  407. int the_ntests = (NTESTS < 1000000) ? 1000 : 1000000;
  408. /* EdDSA */
  409. for (unsigned int t=0; eddsa_sk[t].size(); t++) {
  410. typename EdDSA<Group>::PrivateKey priv(eddsa_sk[t]);
  411. SecureBuffer eddsa_pk2 = priv.pub().serialize();
  412. if (!memeq(SecureBuffer(eddsa_pk[t]), eddsa_pk2)) {
  413. test.fail();
  414. printf(" EdDSA PK vectors disagree.");
  415. printf("\n Correct: ");
  416. for (unsigned i=0; i<eddsa_pk[t].size(); i++) printf("%02x", eddsa_pk[t][i]);
  417. printf("\n Incorrect: ");
  418. for (unsigned i=0; i<eddsa_pk2.size(); i++) printf("%02x", eddsa_pk2[i]);
  419. printf("\n");
  420. }
  421. SecureBuffer sig;
  422. if (eddsa_prehashed[t]) {
  423. typename EdDSA<Group>::PrivateKeyPh priv2(eddsa_sk[t]);
  424. if (priv2.SUPPORTS_CONTEXTS) {
  425. sig = priv2.sign_with_prehash(eddsa_message[t],eddsa_context[t]);
  426. } else {
  427. sig = priv2.sign_with_prehash(eddsa_message[t]);
  428. }
  429. } else {
  430. if (priv.SUPPORTS_CONTEXTS) {
  431. sig = priv.sign(eddsa_message[t],eddsa_context[t]);
  432. } else {
  433. sig = priv.sign(eddsa_message[t]);
  434. }
  435. }
  436. if (!memeq(SecureBuffer(eddsa_sig[t]),sig)) {
  437. test.fail();
  438. printf(" EdDSA sig vectors disagree.");
  439. printf("\n Correct: ");
  440. for (unsigned i=0; i<eddsa_sig[t].size(); i++) printf("%02x", eddsa_sig[t][i]);
  441. printf("\n Incorrect: ");
  442. for (unsigned i=0; i<sig.size(); i++) printf("%02x", sig[i]);
  443. printf("\n");
  444. }
  445. }
  446. /* X25519/X448 */
  447. for (int i=0; i<the_ntests && test.passing_now; i++) {
  448. SecureBuffer n = DhLadder::shared_secret(u,k);
  449. u = k; k = n;
  450. if (i==1-1) {
  451. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1)))) {
  452. test.fail();
  453. printf(" Test vectors disagree at 1.");
  454. }
  455. } else if (i==1000-1) {
  456. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000)))) {
  457. test.fail();
  458. printf(" Test vectors disagree at 1000.");
  459. }
  460. } else if (i==1000000-1) {
  461. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000000)))) {
  462. test.fail();
  463. printf(" Test vectors disagree at 1000000.");
  464. }
  465. }
  466. }
  467. }
  468. static void test_eddsa() {
  469. Test test("EdDSA");
  470. SpongeRng rng(Block("test_eddsa"),SpongeRng::DETERMINISTIC);
  471. for (int i=0; i<NTESTS && test.passing_now; i++) {
  472. typename EdDSA<Group>::PrivateKey priv(rng);
  473. typename EdDSA<Group>::PublicKey pub(priv);
  474. SecureBuffer message(i);
  475. rng.read(message);
  476. SecureBuffer context(priv.SUPPORTS_CONTEXTS ? i%256 : 0);
  477. rng.read(message);
  478. SecureBuffer sig = priv.sign(message,context);
  479. try {
  480. pub.verify(sig,message,context);
  481. } catch(CryptoException) {
  482. test.fail();
  483. printf(" Signature validation failed on sig %d\n", i);
  484. }
  485. }
  486. }
  487. static void run() {
  488. printf("Testing %s:\n",Group::name());
  489. test_arithmetic();
  490. test_elligator();
  491. test_ec();
  492. test_eddsa();
  493. test_cfrg_crypto();
  494. test_cfrg_vectors();
  495. test_crypto();
  496. printf("\n");
  497. }
  498. }; /* template<GroupId GROUP> struct Tests */
  499. #include "vectors.inc.cxx"
  500. int main(int argc, char **argv) {
  501. (void) argc; (void) argv;
  502. run_for_all_curves<Tests>();
  503. if (passing) printf("Passed all tests.\n");
  504. return passing ? 0 : 1;
  505. }