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.
 
 
 
 
 

744 lines
24 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/eddsa.hxx>
  14. #include <decaf/shake.hxx>
  15. #include <stdio.h>
  16. using namespace decaf;
  17. static bool passing = true;
  18. static const long NTESTS = 10000;
  19. #include "ristretto_vectors.inc.cxx"
  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 (unsigned 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 (unsigned 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. FixedArrayBuffer<Point::HASH_BYTES> b3(rng), b4(b3);
  259. t = Point::from_hash(b3);
  260. for (unsigned j=0; j<256; j+=2<<((Group::bits()-1)%8)) {
  261. b4[Point::HASH_BYTES-1] = b3[Point::HASH_BYTES-1] ^ j;
  262. Point u = Point::from_hash(b4);
  263. point_check(test,t,t,t,0,0,t,u,"elligator twiddle high bits");
  264. }
  265. }
  266. }
  267. static void test_ec() {
  268. SpongeRng rng(Block("test_ec"),SpongeRng::DETERMINISTIC);
  269. Test test("EC");
  270. Point id = Point::identity(), base = Point::base();
  271. point_check(test,id,id,id,0,0,Point::from_hash(""),id,"fh0");
  272. unsigned char enc[Point::SER_BYTES] = {0};
  273. if (Group::FIELD_MODULUS_TYPE == 3) {
  274. /* When p == 3 mod 4, the QNR is -1, so u*1^2 = -1 also produces the
  275. * identity.
  276. */
  277. point_check(test,id,id,id,0,0,Point::from_hash("\x01"),id,"fh1");
  278. }
  279. point_check(test,id,id,id,0,0,Point(FixedBlock<sizeof(enc)>(enc)),id,"decode [0]");
  280. try {
  281. enc[0] = 1;
  282. Point f((FixedBlock<sizeof(enc)>(enc)));
  283. test.fail();
  284. printf(" Allowed deserialize of [1]: %d", f==id);
  285. } catch (CryptoException) {
  286. /* ok */
  287. }
  288. if (sqrt_minus_one.size()) {
  289. try {
  290. Point f(sqrt_minus_one);
  291. test.fail();
  292. printf(" Allowed deserialize of [i]: %d", f==id);
  293. } catch (CryptoException) {
  294. /* ok */
  295. }
  296. }
  297. if (minus_sqrt_minus_one.size()) {
  298. try {
  299. Point f(minus_sqrt_minus_one);
  300. test.fail();
  301. printf(" Allowed deserialize of [-i]: %d", f==id);
  302. } catch (CryptoException) {
  303. /* ok */
  304. }
  305. }
  306. for (int i=0; i<NTESTS && test.passing_now; i++) {
  307. Scalar x(rng);
  308. Scalar y(rng);
  309. Point p(rng);
  310. Point q(rng);
  311. Point d1, d2;
  312. SecureBuffer buffer(2*Point::HASH_BYTES);
  313. rng.read(buffer);
  314. Point r = Point::from_hash(buffer);
  315. try {
  316. point_check(test,p,q,r,0,0,p,Point(p.serialize()),"round-trip");
  317. } catch (CryptoException) {
  318. test.fail();
  319. printf(" Round-trip raised CryptoException!\n");
  320. }
  321. Point pp = p.debugging_torque().debugging_pscale(rng);
  322. if (!memeq(pp.serialize(),p.serialize())) {
  323. test.fail();
  324. printf(" Fail torque seq test\n");
  325. }
  326. if (!memeq((p-pp).serialize(),id.serialize())) {
  327. test.fail();
  328. printf(" Fail torque id test\n");
  329. }
  330. if (!memeq((p-p).serialize(),id.serialize())) {
  331. test.fail();
  332. printf(" Fail id test\n");
  333. }
  334. point_check(test,p,q,r,0,0,p,pp,"torque eq");
  335. point_check(test,p,q,r,0,0,p+q,q+p,"commute add");
  336. point_check(test,p,q,r,0,0,(p-q)+q,p,"correct sub");
  337. point_check(test,p,q,r,0,0,p+(q+r),(p+q)+r,"assoc add");
  338. point_check(test,p,q,r,0,0,p.times_two(),p+p,"dbl add");
  339. if (i%10) continue;
  340. point_check(test,p,q,r,0,0,p.times_two(),p*Scalar(2),"add times two");
  341. point_check(test,p,q,r,x,0,x*(p+q),x*p+x*q,"distr mul");
  342. point_check(test,p,q,r,x,y,(x*y)*p,x*(y*p),"assoc mul");
  343. point_check(test,p,q,r,x,y,x*p+y*q,Point::double_scalarmul(x,p,y,q),"double mul");
  344. p.dual_scalarmul(d1,d2,x,y);
  345. point_check(test,p,q,r,x,y,x*p,d1,"dual mul 1");
  346. point_check(test,p,q,r,x,y,y*p,d2,"dual mul 2");
  347. point_check(test,base,q,r,x,y,x*base+y*q,q.non_secret_combo_with_base(y,x),"ds vt mul");
  348. point_check(test,p,q,r,x,0,Precomputed(p)*x,p*x,"precomp mul");
  349. point_check(test,p,q,r,0,0,r,
  350. Point::from_hash(Buffer(buffer).slice(0,Point::HASH_BYTES))
  351. + Point::from_hash(Buffer(buffer).slice(Point::HASH_BYTES,Point::HASH_BYTES)),
  352. "unih = hash+add"
  353. );
  354. try {
  355. point_check(test,p,q,r,x,0,Point(x.direct_scalarmul(p.serialize())),x*p,"direct mul");
  356. } catch (CryptoException) {
  357. printf(" Direct mul raised CryptoException!\n");
  358. test.fail();
  359. }
  360. q=p;
  361. for (int j=1; j<Group::REMOVED_COFACTOR; j<<=1) q = q.times_two();
  362. decaf_error_t error = r.decode_like_eddsa_and_mul_by_ratio_noexcept(
  363. p.mul_by_ratio_and_encode_like_eddsa()
  364. );
  365. if (error != DECAF_SUCCESS) {
  366. test.fail();
  367. printf(" Decode like EdDSA failed.");
  368. }
  369. point_check(test,-q,q,r,i,0,q,r,"Encode like EdDSA round-trip");
  370. }
  371. }
  372. static const uint8_t rfc7748_1[DhLadder::PUBLIC_BYTES];
  373. static const uint8_t rfc7748_1000[DhLadder::PUBLIC_BYTES];
  374. static const uint8_t rfc7748_1000000[DhLadder::PUBLIC_BYTES];
  375. static void test_cfrg_crypto() {
  376. Test test("CFRG crypto");
  377. SpongeRng rng(Block("test_cfrg_crypto"),SpongeRng::DETERMINISTIC);
  378. {
  379. FixedArrayBuffer<DhLadder::PUBLIC_BYTES> base, out;
  380. FixedArrayBuffer<DhLadder::PRIVATE_BYTES> s1(rng);
  381. decaf_error_t e = DhLadder::shared_secret_noexcept(out,base,s1);
  382. if (e != DECAF_FAILURE) {
  383. test.fail();
  384. printf(" Multiply by 0 didn't give an error\n");
  385. }
  386. if (!out.contents_equal(base)) {
  387. test.fail();
  388. printf(" Multiply by 0 didn't give 0\n");
  389. }
  390. }
  391. for (int i=0; i<NTESTS && test.passing_now; i++) {
  392. FixedArrayBuffer<DhLadder::PUBLIC_BYTES> base(rng);
  393. FixedArrayBuffer<DhLadder::PRIVATE_BYTES> s1(rng), s2(rng);
  394. SecureBuffer p1 = DhLadder::shared_secret(base,s1);
  395. SecureBuffer p2 = DhLadder::shared_secret(base,s2);
  396. SecureBuffer ss1 = DhLadder::shared_secret(p2,s1);
  397. SecureBuffer ss2 = DhLadder::shared_secret(p1,s2);
  398. if (!memeq(ss1,ss2)) {
  399. test.fail();
  400. printf(" Shared secrets disagree on iteration %d.\n",i);
  401. }
  402. p1 = DhLadder::shared_secret(DhLadder::base_point(),s1);
  403. p2 = DhLadder::derive_public_key(s1);
  404. if (!memeq(p1,p2)) {
  405. test.fail();
  406. printf(" Public keys disagree on iteration %d.\n Ladder public key: ",i);
  407. for (unsigned j=0; j<s1.size(); j++) { printf("%02x",p1[j]); }
  408. printf("\n Derive public key: ");
  409. for (unsigned j=0; j<s1.size(); j++) { printf("%02x",p2[j]); }
  410. printf("\n");
  411. }
  412. }
  413. }
  414. static const bool eddsa_prehashed[];
  415. static const Block eddsa_sk[], eddsa_pk[], eddsa_message[], eddsa_context[], eddsa_sig[];
  416. static void test_cfrg_vectors() {
  417. Test test("CFRG test vectors");
  418. SecureBuffer k = DhLadder::base_point();
  419. SecureBuffer u = DhLadder::base_point();
  420. int the_ntests = (NTESTS < 1000000) ? 1000 : 1000000;
  421. /* EdDSA */
  422. for (unsigned int t=0; eddsa_sk[t].size(); t++) {
  423. typename EdDSA<Group>::PrivateKey priv(eddsa_sk[t]);
  424. SecureBuffer eddsa_pk2 = priv.pub().serialize();
  425. if (!memeq(SecureBuffer(eddsa_pk[t]), eddsa_pk2)) {
  426. test.fail();
  427. printf(" EdDSA PK vectors #%d disagree.", t);
  428. printf("\n Correct: ");
  429. for (unsigned i=0; i<eddsa_pk[t].size(); i++) printf("%02x", eddsa_pk[t][i]);
  430. printf("\n Incorrect: ");
  431. for (unsigned i=0; i<eddsa_pk2.size(); i++) printf("%02x", eddsa_pk2[i]);
  432. printf("\n");
  433. }
  434. SecureBuffer sig;
  435. if (eddsa_prehashed[t]) {
  436. typename EdDSA<Group>::PrivateKeyPh priv2(eddsa_sk[t]);
  437. sig = priv2.sign_with_prehash(eddsa_message[t],eddsa_context[t]);
  438. } else {
  439. sig = priv.sign(eddsa_message[t],eddsa_context[t]);
  440. }
  441. if (!memeq(SecureBuffer(eddsa_sig[t]),sig)) {
  442. test.fail();
  443. printf(" EdDSA sig vectors disagree.");
  444. printf("\n Correct: ");
  445. for (unsigned i=0; i<eddsa_sig[t].size(); i++) printf("%02x", eddsa_sig[t][i]);
  446. printf("\n Incorrect: ");
  447. for (unsigned i=0; i<sig.size(); i++) printf("%02x", sig[i]);
  448. printf("\n");
  449. }
  450. }
  451. /* X25519/X448 */
  452. for (int i=0; i<the_ntests && test.passing_now; i++) {
  453. SecureBuffer n = DhLadder::shared_secret(u,k);
  454. u = k; k = n;
  455. if (i==1-1) {
  456. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1)))) {
  457. test.fail();
  458. printf(" Test vectors disagree at 1.");
  459. }
  460. } else if (i==1000-1) {
  461. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000)))) {
  462. test.fail();
  463. printf(" Test vectors disagree at 1000.");
  464. }
  465. } else if (i==1000000-1) {
  466. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000000)))) {
  467. test.fail();
  468. printf(" Test vectors disagree at 1000000.");
  469. }
  470. }
  471. }
  472. }
  473. static void test_eddsa() {
  474. Test test("EdDSA");
  475. SpongeRng rng(Block("test_eddsa"),SpongeRng::DETERMINISTIC);
  476. for (int i=0; i<NTESTS && test.passing_now; i++) {
  477. typename EdDSA<Group>::PrivateKey priv(rng);
  478. typename EdDSA<Group>::PublicKey pub(priv);
  479. SecureBuffer message(i);
  480. rng.read(message);
  481. SecureBuffer context(i%256);
  482. rng.read(context);
  483. SecureBuffer sig = priv.sign(message,context);
  484. try {
  485. pub.verify(sig,message,context);
  486. } catch(CryptoException) {
  487. test.fail();
  488. printf(" Signature validation failed on sig %d\n", i);
  489. }
  490. /* Test encode_like and torque */
  491. Point p(rng);
  492. SecureBuffer p1 = p.mul_by_ratio_and_encode_like_eddsa();
  493. SecureBuffer p2 = p.debugging_torque().mul_by_ratio_and_encode_like_eddsa();
  494. if (!memeq(p1,p2)) {
  495. test.fail();
  496. printf(" Torque and encode like EdDSA failed\n");
  497. }
  498. SecureBuffer p3 = p.mul_by_ratio_and_encode_like_ladder();
  499. SecureBuffer p4 = p.debugging_torque().mul_by_ratio_and_encode_like_ladder();
  500. if (!memeq(p3,p4)) {
  501. test.fail();
  502. printf(" Torque and encode like ladder failed\n");
  503. }
  504. }
  505. }
  506. /* Thanks Johan Pascal */
  507. static void test_convert_eddsa_to_x() {
  508. Test test("ECDH using EdDSA keys");
  509. SpongeRng rng(Block("test_x_on_eddsa_key"),SpongeRng::DETERMINISTIC);
  510. for (int i=0; i<NTESTS && test.passing_now; i++) {
  511. /* generate 2 pairs of EdDSA keys */
  512. typename EdDSA<Group>::PrivateKey alice_priv(rng);
  513. typename EdDSA<Group>::PublicKey alice_pub(alice_priv);
  514. typename EdDSA<Group>::PrivateKey bob_priv(rng);
  515. typename EdDSA<Group>::PublicKey bob_pub(bob_priv);
  516. /* convert them to ECDH format
  517. * check public key value by computing it from direct conversion and regeneration from converted private)
  518. */
  519. SecureBuffer alice_priv_x = alice_priv.convert_to_x();
  520. SecureBuffer alice_pub_x_conversion = alice_pub.convert_to_x();
  521. SecureBuffer alice_pub_x_generated = DhLadder::derive_public_key(alice_priv_x);
  522. if (!memeq(alice_pub_x_conversion, alice_pub_x_generated)) {
  523. test.fail();
  524. printf(" Ed2X Public key conversion and regeneration from converted private key differs.\n");
  525. }
  526. SecureBuffer bob_priv_x = bob_priv.convert_to_x();
  527. SecureBuffer bob_pub_x_conversion = bob_pub.convert_to_x();
  528. SecureBuffer bob_pub_x_generated = DhLadder::derive_public_key(bob_priv_x);
  529. if (!memeq(bob_pub_x_conversion, bob_pub_x_generated)) {
  530. test.fail();
  531. printf(" Ed2X Public key conversion and regeneration from converted private key differs.\n");
  532. }
  533. /* compute shared secrets and check they match */
  534. SecureBuffer alice_shared = DhLadder::shared_secret(bob_pub_x_conversion, alice_priv_x);
  535. SecureBuffer bob_shared = DhLadder::shared_secret(alice_pub_x_conversion, bob_priv_x);
  536. if (!memeq(alice_shared, bob_shared)) {
  537. test.fail();
  538. printf(" ECDH shared secret mismatch.\n");
  539. }
  540. }
  541. }
  542. static void test_dalek_vectors() {
  543. Test test("Test vectors from Dalek");
  544. Point p = Point::base(), q;
  545. for (unsigned i=0; i<base_multiples<Group>::count; i++) {
  546. if (!decaf_memeq(q.serialize().data(),base_multiples<Group>::values[i],Point::SER_BYTES)) {
  547. test.fail();
  548. printf(" Failed test vector for %d * base point.\n", i);
  549. }
  550. q += p;
  551. }
  552. for (unsigned i=0; i<elligator_examples<Group>::count; i++) {
  553. Point r = Point::from_hash(FixedBlock<Point::HASH_BYTES>(elligator_examples<Group>::inputs[i]));
  554. Point s = Point(FixedBlock<Point::SER_BYTES>(elligator_examples<Group>::outputs[i]));
  555. point_check(test,r,r,r,0,0,r,s,"elligator test vector");
  556. }
  557. }
  558. static void run() {
  559. printf("Testing %s:\n",Group::name());
  560. test_arithmetic();
  561. test_elligator();
  562. test_ec();
  563. test_eddsa();
  564. test_convert_eddsa_to_x();
  565. test_cfrg_crypto();
  566. test_cfrg_vectors();
  567. test_dalek_vectors();
  568. printf("\n");
  569. }
  570. }; /* template<GroupId GROUP> struct Tests */
  571. template<typename T>
  572. static void test_xof() {
  573. /* TODO: more testing of XOFs */
  574. Test test("XOF");
  575. SpongeRng rng(Block("test_xof"),SpongeRng::DETERMINISTIC);
  576. FixedArrayBuffer<1024> a,b,c;
  577. rng.read(c);
  578. T s1, s2;
  579. unsigned i;
  580. for (i=0; i<c.size(); i++) s1.update(c.slice(i,1));
  581. s2.update(c);
  582. for (i=0; i<a.size(); i++) s1.output(a.slice(i,1));
  583. s2.output(b);
  584. if (!a.contents_equal(b)) {
  585. test.fail();
  586. printf(" Buffers aren't equal!\n");
  587. }
  588. }
  589. static void test_rng() {
  590. Test test("RNG");
  591. SpongeRng rng_d1(Block("test_rng"),SpongeRng::DETERMINISTIC);
  592. SpongeRng rng_d2(Block("test_rng"),SpongeRng::DETERMINISTIC);
  593. SpongeRng rng_d3(Block("best_rng"),SpongeRng::DETERMINISTIC);
  594. SpongeRng rng_n1;
  595. SpongeRng rng_n2;
  596. SecureBuffer s1,s2,s3;
  597. for (int i=0; i<5; i++) {
  598. s1 = rng_d1.read(16<<i);
  599. s2 = rng_d2.read(16<<i);
  600. s3 = rng_d3.read(16<<i);
  601. if (s1 != s2) {
  602. test.fail();
  603. printf(" Deterministic RNG didn't match!\n");
  604. }
  605. if (s1 == s3) {
  606. test.fail();
  607. printf(" Deterministic matched with different data!\n");
  608. }
  609. rng_d1.stir("hello");
  610. rng_d2.stir("hello");
  611. rng_d3.stir("hello");
  612. s1 = rng_n1.read(16<<i);
  613. s2 = rng_n2.read(16<<i);
  614. if (s1 == s2) {
  615. test.fail();
  616. printf(" Nondeterministic RNG matched!\n");
  617. }
  618. }
  619. rng_d1.stir("hello");
  620. rng_d2.stir("jello");
  621. s1 = rng_d1.read(16);
  622. s2 = rng_d2.read(16);
  623. if (s1 == s2) {
  624. test.fail();
  625. printf(" Deterministic matched with different data!\n");
  626. }
  627. }
  628. #include "vectors.inc.cxx"
  629. int main(int argc, char **argv) {
  630. (void) argc; (void) argv;
  631. test_rng();
  632. test_xof<SHAKE<128> >();
  633. test_xof<SHAKE<256> >();
  634. printf("\n");
  635. run_for_all_curves<Tests>();
  636. if (passing) printf("Passed all tests.\n");
  637. return passing ? 0 : 1;
  638. }