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.
 
 
 
 
 

807 lines
27 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 const bool eddsa_verify_should_succeed[];
  417. static void test_cfrg_vectors() {
  418. Test test("CFRG test vectors");
  419. SecureBuffer k = DhLadder::base_point();
  420. SecureBuffer u = DhLadder::base_point();
  421. int the_ntests = (NTESTS < 1000000) ? 1000 : 1000000;
  422. /* EdDSA */
  423. for (unsigned int t=0; t<sizeof(eddsa_sk)/sizeof(eddsa_sk[0]); t++) {
  424. if (eddsa_sk[t].size()) {
  425. typename EdDSA<Group>::PrivateKey priv(eddsa_sk[t]);
  426. SecureBuffer eddsa_pk2 = priv.pub().serialize();
  427. if (!memeq(SecureBuffer(eddsa_pk[t]), eddsa_pk2)) {
  428. test.fail();
  429. printf(" EdDSA PK vectors #%d disagree.", t);
  430. printf("\n Correct: ");
  431. for (unsigned i=0; i<eddsa_pk[t].size(); i++) printf("%02x", eddsa_pk[t][i]);
  432. printf("\n Incorrect: ");
  433. for (unsigned i=0; i<eddsa_pk2.size(); i++) printf("%02x", eddsa_pk2[i]);
  434. printf("\n");
  435. }
  436. SecureBuffer sig;
  437. if (eddsa_prehashed[t]) {
  438. typename EdDSA<Group>::PrivateKeyPh priv2(eddsa_sk[t]);
  439. sig = priv2.sign_with_prehash(eddsa_message[t],eddsa_context[t]);
  440. } else {
  441. sig = priv.sign(eddsa_message[t],eddsa_context[t]);
  442. }
  443. if (!memeq(SecureBuffer(eddsa_sig[t]),sig)) {
  444. test.fail();
  445. printf(" EdDSA sig vectors #%d disagree.", t);
  446. printf("\n Correct: ");
  447. for (unsigned i=0; i<eddsa_sig[t].size(); i++) printf("%02x", eddsa_sig[t][i]);
  448. printf("\n Incorrect: ");
  449. for (unsigned i=0; i<sig.size(); i++) printf("%02x", sig[i]);
  450. printf("\n");
  451. }
  452. }
  453. bool verified;
  454. try {
  455. typename EdDSA<Group>::PublicKey pub(eddsa_pk[t]);
  456. if (eddsa_prehashed[t]) {
  457. pub.verify_with_prehash(eddsa_sig[t], eddsa_message[t], eddsa_context[t]);
  458. } else {
  459. pub.verify(eddsa_sig[t], eddsa_message[t], eddsa_context[t]);
  460. }
  461. verified = true;
  462. } catch(CryptoException&) {
  463. verified = false;
  464. }
  465. if (verified != eddsa_verify_should_succeed[t]) {
  466. test.fail();
  467. printf(" EdDSA Verify vector #%d disagree: verify %s but should %s\n",
  468. t, verified ? "passed" : "failed",
  469. eddsa_verify_should_succeed[t] ? "pass" : "fail");
  470. }
  471. }
  472. /* X25519/X448 */
  473. for (int i=0; i<the_ntests && test.passing_now; i++) {
  474. SecureBuffer n = DhLadder::shared_secret(u,k);
  475. u = k; k = n;
  476. if (i==1-1) {
  477. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1)))) {
  478. test.fail();
  479. printf(" Test vectors disagree at 1.");
  480. }
  481. } else if (i==1000-1) {
  482. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000)))) {
  483. test.fail();
  484. printf(" Test vectors disagree at 1000.");
  485. }
  486. } else if (i==1000000-1) {
  487. if (!memeq(k,SecureBuffer(FixedBlock<DhLadder::PUBLIC_BYTES>(rfc7748_1000000)))) {
  488. test.fail();
  489. printf(" Test vectors disagree at 1000000.");
  490. }
  491. }
  492. }
  493. }
  494. static void test_eddsa() {
  495. Test test("EdDSA");
  496. SpongeRng rng(Block("test_eddsa"),SpongeRng::DETERMINISTIC);
  497. for (int i=0; i<NTESTS && test.passing_now; i++) {
  498. typename EdDSA<Group>::PrivateKey priv(rng);
  499. typename EdDSA<Group>::PublicKey pub(priv);
  500. SecureBuffer message(i);
  501. rng.read(message);
  502. SecureBuffer context(i%256);
  503. rng.read(context);
  504. SecureBuffer sig = priv.sign(message,context);
  505. try {
  506. pub.verify(sig,message,context);
  507. } catch(CryptoException&) {
  508. test.fail();
  509. printf(" Signature validation failed on sig %d\n", i);
  510. }
  511. try {
  512. sig[(i/8) % sig.size()] ^= 1<<(i%8);
  513. pub.verify(sig,message,context);
  514. test.fail();
  515. printf(" Signature validation passed incorrectly on corrupted sig %d\n", i);
  516. } catch(CryptoException&) {}
  517. sig[(i/8) % sig.size()] ^= 1<<(i%8);
  518. try {
  519. const int size = EdDSA<Group>::PublicKey::SER_BYTES;
  520. uint8_t ser[size];
  521. pub.serialize_into(ser);
  522. ser[(i/8) % size] ^= 1<<(i%8);
  523. typename EdDSA<Group>::PublicKey pub2((FixedBlock<size>(ser)));
  524. pub2.verify(sig,message,context);
  525. test.fail();
  526. printf(" Signature validation passed incorrectly on corrupted pubkey %d\n", i);
  527. } catch(CryptoException&) {}
  528. if (message.size() > 0) {
  529. try {
  530. message[(i/8) % message.size()] ^= 1<<(i%8);
  531. pub.verify(sig,message,context);
  532. test.fail();
  533. printf(" Signature validation passed incorrectly on corrupted message %d\n", i);
  534. } catch(CryptoException&) {}
  535. message[(i/8) % message.size()] ^= 1<<(i%8);
  536. }
  537. if (context.size() > 0) {
  538. try {
  539. context[(i/8) % context.size()] ^= 1<<(i%8);
  540. pub.verify(sig,message,context);
  541. test.fail();
  542. printf(" Signature validation passed incorrectly on corrupted message %d\n", i);
  543. } catch(CryptoException&) {}
  544. context[(i/8) % context.size()] ^= 1<<(i%8);
  545. }
  546. /* Test encode_like and torque */
  547. Point p(rng);
  548. SecureBuffer p1 = p.mul_by_ratio_and_encode_like_eddsa();
  549. SecureBuffer p2 = p.debugging_torque().mul_by_ratio_and_encode_like_eddsa();
  550. if (!memeq(p1,p2)) {
  551. test.fail();
  552. printf(" Torque and encode like EdDSA failed\n");
  553. }
  554. SecureBuffer p3 = p.mul_by_ratio_and_encode_like_ladder();
  555. SecureBuffer p4 = p.debugging_torque().mul_by_ratio_and_encode_like_ladder();
  556. if (!memeq(p3,p4)) {
  557. test.fail();
  558. printf(" Torque and encode like ladder failed\n");
  559. }
  560. }
  561. }
  562. /* Thanks Johan Pascal */
  563. static void test_convert_eddsa_to_x() {
  564. Test test("ECDH using EdDSA keys");
  565. SpongeRng rng(Block("test_x_on_eddsa_key"),SpongeRng::DETERMINISTIC);
  566. for (int i=0; i<NTESTS && test.passing_now; i++) {
  567. /* generate 2 pairs of EdDSA keys */
  568. typename EdDSA<Group>::PrivateKey alice_priv(rng);
  569. typename EdDSA<Group>::PublicKey alice_pub(alice_priv);
  570. typename EdDSA<Group>::PrivateKey bob_priv(rng);
  571. typename EdDSA<Group>::PublicKey bob_pub(bob_priv);
  572. /* convert them to ECDH format
  573. * check public key value by computing it from direct conversion and regeneration from converted private)
  574. */
  575. SecureBuffer alice_priv_x = alice_priv.convert_to_x();
  576. SecureBuffer alice_pub_x_conversion = alice_pub.convert_to_x();
  577. SecureBuffer alice_pub_x_generated = DhLadder::derive_public_key(alice_priv_x);
  578. if (!memeq(alice_pub_x_conversion, alice_pub_x_generated)) {
  579. test.fail();
  580. printf(" Ed2X Public key conversion and regeneration from converted private key differs.\n");
  581. }
  582. SecureBuffer bob_priv_x = bob_priv.convert_to_x();
  583. SecureBuffer bob_pub_x_conversion = bob_pub.convert_to_x();
  584. SecureBuffer bob_pub_x_generated = DhLadder::derive_public_key(bob_priv_x);
  585. if (!memeq(bob_pub_x_conversion, bob_pub_x_generated)) {
  586. test.fail();
  587. printf(" Ed2X Public key conversion and regeneration from converted private key differs.\n");
  588. }
  589. /* compute shared secrets and check they match */
  590. SecureBuffer alice_shared = DhLadder::shared_secret(bob_pub_x_conversion, alice_priv_x);
  591. SecureBuffer bob_shared = DhLadder::shared_secret(alice_pub_x_conversion, bob_priv_x);
  592. if (!memeq(alice_shared, bob_shared)) {
  593. test.fail();
  594. printf(" ECDH shared secret mismatch.\n");
  595. }
  596. }
  597. }
  598. static void test_dalek_vectors() {
  599. Test test("Test vectors from Dalek");
  600. Point p = Point::base(), q;
  601. for (unsigned i=0; i<base_multiples<Group>::count; i++) {
  602. if (!decaf_memeq(q.serialize().data(),base_multiples<Group>::values[i],Point::SER_BYTES)) {
  603. test.fail();
  604. printf(" Failed test vector for %d * base point.\n", i);
  605. }
  606. q += p;
  607. }
  608. for (unsigned i=0; i<elligator_examples<Group>::count; i++) {
  609. Point r = Point::from_hash(FixedBlock<Point::HASH_BYTES>(elligator_examples<Group>::inputs[i]));
  610. Point s = Point(FixedBlock<Point::SER_BYTES>(elligator_examples<Group>::outputs[i]));
  611. point_check(test,r,r,r,0,0,r,s,"elligator test vector");
  612. }
  613. }
  614. static void run() {
  615. printf("Testing %s:\n",Group::name());
  616. test_arithmetic();
  617. test_elligator();
  618. test_ec();
  619. test_eddsa();
  620. test_convert_eddsa_to_x();
  621. test_cfrg_crypto();
  622. test_cfrg_vectors();
  623. test_dalek_vectors();
  624. printf("\n");
  625. }
  626. }; /* template<GroupId GROUP> struct Tests */
  627. template<typename T>
  628. static void test_xof() {
  629. /* TODO: more testing of XOFs */
  630. Test test("XOF");
  631. SpongeRng rng(Block("test_xof"),SpongeRng::DETERMINISTIC);
  632. FixedArrayBuffer<1024> a,b,c;
  633. rng.read(c);
  634. T s1, s2;
  635. unsigned i;
  636. for (i=0; i<c.size(); i++) s1.update(c.slice(i,1));
  637. s2.update(c);
  638. for (i=0; i<a.size(); i++) s1.output(a.slice(i,1));
  639. s2.output(b);
  640. if (!a.contents_equal(b)) {
  641. test.fail();
  642. printf(" Buffers aren't equal!\n");
  643. }
  644. }
  645. static void test_rng() {
  646. Test test("RNG");
  647. SpongeRng rng_d1(Block("test_rng"),SpongeRng::DETERMINISTIC);
  648. SpongeRng rng_d2(Block("test_rng"),SpongeRng::DETERMINISTIC);
  649. SpongeRng rng_d3(Block("best_rng"),SpongeRng::DETERMINISTIC);
  650. SpongeRng rng_n1;
  651. SpongeRng rng_n2;
  652. SecureBuffer s1,s2,s3;
  653. for (int i=0; i<5; i++) {
  654. s1 = rng_d1.read(16<<i);
  655. s2 = rng_d2.read(16<<i);
  656. s3 = rng_d3.read(16<<i);
  657. if (s1 != s2) {
  658. test.fail();
  659. printf(" Deterministic RNG didn't match!\n");
  660. }
  661. if (s1 == s3) {
  662. test.fail();
  663. printf(" Deterministic matched with different data!\n");
  664. }
  665. rng_d1.stir("hello");
  666. rng_d2.stir("hello");
  667. rng_d3.stir("hello");
  668. s1 = rng_n1.read(16<<i);
  669. s2 = rng_n2.read(16<<i);
  670. if (s1 == s2) {
  671. test.fail();
  672. printf(" Nondeterministic RNG matched!\n");
  673. }
  674. }
  675. rng_d1.stir("hello");
  676. rng_d2.stir("jello");
  677. s1 = rng_d1.read(16);
  678. s2 = rng_d2.read(16);
  679. if (s1 == s2) {
  680. test.fail();
  681. printf(" Deterministic matched with different data!\n");
  682. }
  683. }
  684. #include "vectors.inc.cxx"
  685. int main(int argc, char **argv) {
  686. (void) argc; (void) argv;
  687. test_rng();
  688. test_xof<SHAKE<128> >();
  689. test_xof<SHAKE<256> >();
  690. printf("\n");
  691. run_for_all_curves<Tests>();
  692. if (passing) printf("Passed all tests.\n");
  693. return passing ? 0 : 1;
  694. }