ecdsa.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. /**
  2. * Copyright (c) 2013-2014 Tomas Dzetkulic
  3. * Copyright (c) 2013-2014 Pavol Rusnak
  4. * Copyright (c) 2015 Jochen Hoenicke
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining
  7. * a copy of this software and associated documentation files (the "Software"),
  8. * to deal in the Software without restriction, including without limitation
  9. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. * and/or sell copies of the Software, and to permit persons to whom the
  11. * Software is furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included
  14. * in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
  20. * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  21. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  22. * OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. #include <assert.h>
  25. #include <stdint.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include "address.h"
  29. #include "base58.h"
  30. #include "bignum.h"
  31. #include "ecdsa.h"
  32. #include "hmac.h"
  33. #include "memzero.h"
  34. #include "rand.h"
  35. #include "rfc6979.h"
  36. #include "secp256k1.h"
  37. // Set cp2 = cp1
  38. void point_copy(const curve_point *cp1, curve_point *cp2) { *cp2 = *cp1; }
  39. // cp2 = cp1 + cp2
  40. void point_add(const ecdsa_curve *curve, const curve_point *cp1,
  41. curve_point *cp2) {
  42. bignum256 lambda = {0}, inv = {0}, xr = {0}, yr = {0};
  43. if (point_is_infinity(cp1)) {
  44. return;
  45. }
  46. if (point_is_infinity(cp2)) {
  47. point_copy(cp1, cp2);
  48. return;
  49. }
  50. if (point_is_equal(cp1, cp2)) {
  51. point_double(curve, cp2);
  52. return;
  53. }
  54. if (point_is_negative_of(cp1, cp2)) {
  55. point_set_infinity(cp2);
  56. return;
  57. }
  58. // lambda = (y2 - y1) / (x2 - x1)
  59. bn_subtractmod(&(cp2->x), &(cp1->x), &inv, &curve->prime);
  60. bn_inverse(&inv, &curve->prime);
  61. bn_subtractmod(&(cp2->y), &(cp1->y), &lambda, &curve->prime);
  62. bn_multiply(&inv, &lambda, &curve->prime);
  63. // xr = lambda^2 - x1 - x2
  64. xr = lambda;
  65. bn_multiply(&xr, &xr, &curve->prime);
  66. yr = cp1->x;
  67. bn_addmod(&yr, &(cp2->x), &curve->prime);
  68. bn_subtractmod(&xr, &yr, &xr, &curve->prime);
  69. bn_fast_mod(&xr, &curve->prime);
  70. bn_mod(&xr, &curve->prime);
  71. // yr = lambda (x1 - xr) - y1
  72. bn_subtractmod(&(cp1->x), &xr, &yr, &curve->prime);
  73. bn_multiply(&lambda, &yr, &curve->prime);
  74. bn_subtractmod(&yr, &(cp1->y), &yr, &curve->prime);
  75. bn_fast_mod(&yr, &curve->prime);
  76. bn_mod(&yr, &curve->prime);
  77. cp2->x = xr;
  78. cp2->y = yr;
  79. }
  80. // cp = cp + cp
  81. void point_double(const ecdsa_curve *curve, curve_point *cp) {
  82. bignum256 lambda = {0}, xr = {0}, yr = {0};
  83. if (point_is_infinity(cp)) {
  84. return;
  85. }
  86. if (bn_is_zero(&(cp->y))) {
  87. point_set_infinity(cp);
  88. return;
  89. }
  90. // lambda = (3 x^2 + a) / (2 y)
  91. lambda = cp->y;
  92. bn_mult_k(&lambda, 2, &curve->prime);
  93. bn_fast_mod(&lambda, &curve->prime);
  94. bn_mod(&lambda, &curve->prime);
  95. bn_inverse(&lambda, &curve->prime);
  96. xr = cp->x;
  97. bn_multiply(&xr, &xr, &curve->prime);
  98. bn_mult_k(&xr, 3, &curve->prime);
  99. bn_subi(&xr, -curve->a, &curve->prime);
  100. bn_multiply(&xr, &lambda, &curve->prime);
  101. // xr = lambda^2 - 2*x
  102. xr = lambda;
  103. bn_multiply(&xr, &xr, &curve->prime);
  104. yr = cp->x;
  105. bn_lshift(&yr);
  106. bn_subtractmod(&xr, &yr, &xr, &curve->prime);
  107. bn_fast_mod(&xr, &curve->prime);
  108. bn_mod(&xr, &curve->prime);
  109. // yr = lambda (x - xr) - y
  110. bn_subtractmod(&(cp->x), &xr, &yr, &curve->prime);
  111. bn_multiply(&lambda, &yr, &curve->prime);
  112. bn_subtractmod(&yr, &(cp->y), &yr, &curve->prime);
  113. bn_fast_mod(&yr, &curve->prime);
  114. bn_mod(&yr, &curve->prime);
  115. cp->x = xr;
  116. cp->y = yr;
  117. }
  118. // set point to internal representation of point at infinity
  119. void point_set_infinity(curve_point *p) {
  120. bn_zero(&(p->x));
  121. bn_zero(&(p->y));
  122. }
  123. // return true iff p represent point at infinity
  124. // both coords are zero in internal representation
  125. int point_is_infinity(const curve_point *p) {
  126. return bn_is_zero(&(p->x)) && bn_is_zero(&(p->y));
  127. }
  128. // return true iff both points are equal
  129. int point_is_equal(const curve_point *p, const curve_point *q) {
  130. return bn_is_equal(&(p->x), &(q->x)) && bn_is_equal(&(p->y), &(q->y));
  131. }
  132. // returns true iff p == -q
  133. // expects p and q be valid points on curve other than point at infinity
  134. int point_is_negative_of(const curve_point *p, const curve_point *q) {
  135. // if P == (x, y), then -P would be (x, -y) on this curve
  136. if (!bn_is_equal(&(p->x), &(q->x))) {
  137. return 0;
  138. }
  139. // we shouldn't hit this for a valid point
  140. if (bn_is_zero(&(p->y))) {
  141. return 0;
  142. }
  143. return !bn_is_equal(&(p->y), &(q->y));
  144. }
  145. typedef struct jacobian_curve_point {
  146. bignum256 x, y, z;
  147. } jacobian_curve_point;
  148. // generate random K for signing/side-channel noise
  149. static void generate_k_random(bignum256 *k, const bignum256 *prime) {
  150. do {
  151. int i = 0;
  152. for (i = 0; i < 8; i++) {
  153. k->val[i] = random32() & ((1u << BN_BITS_PER_LIMB) - 1);
  154. }
  155. k->val[8] = random32() & ((1u << BN_BITS_LAST_LIMB) - 1);
  156. // check that k is in range and not zero.
  157. } while (bn_is_zero(k) || !bn_is_less(k, prime));
  158. }
  159. void curve_to_jacobian(const curve_point *p, jacobian_curve_point *jp,
  160. const bignum256 *prime) {
  161. // randomize z coordinate
  162. generate_k_random(&jp->z, prime);
  163. jp->x = jp->z;
  164. bn_multiply(&jp->z, &jp->x, prime);
  165. // x = z^2
  166. jp->y = jp->x;
  167. bn_multiply(&jp->z, &jp->y, prime);
  168. // y = z^3
  169. bn_multiply(&p->x, &jp->x, prime);
  170. bn_multiply(&p->y, &jp->y, prime);
  171. }
  172. void jacobian_to_curve(const jacobian_curve_point *jp, curve_point *p,
  173. const bignum256 *prime) {
  174. p->y = jp->z;
  175. bn_inverse(&p->y, prime);
  176. // p->y = z^-1
  177. p->x = p->y;
  178. bn_multiply(&p->x, &p->x, prime);
  179. // p->x = z^-2
  180. bn_multiply(&p->x, &p->y, prime);
  181. // p->y = z^-3
  182. bn_multiply(&jp->x, &p->x, prime);
  183. // p->x = jp->x * z^-2
  184. bn_multiply(&jp->y, &p->y, prime);
  185. // p->y = jp->y * z^-3
  186. bn_mod(&p->x, prime);
  187. bn_mod(&p->y, prime);
  188. }
  189. void point_jacobian_add(const curve_point *p1, jacobian_curve_point *p2,
  190. const ecdsa_curve *curve) {
  191. bignum256 r = {0}, h = {0}, r2 = {0};
  192. bignum256 hcby = {0}, hsqx = {0};
  193. bignum256 xz = {0}, yz = {0}, az = {0};
  194. int is_doubling = 0;
  195. const bignum256 *prime = &curve->prime;
  196. int a = curve->a;
  197. assert(-3 <= a && a <= 0);
  198. /* First we bring p1 to the same denominator:
  199. * x1' := x1 * z2^2
  200. * y1' := y1 * z2^3
  201. */
  202. /*
  203. * lambda = ((y1' - y2)/z2^3) / ((x1' - x2)/z2^2)
  204. * = (y1' - y2) / (x1' - x2) z2
  205. * x3/z3^2 = lambda^2 - (x1' + x2)/z2^2
  206. * y3/z3^3 = 1/2 lambda * (2x3/z3^2 - (x1' + x2)/z2^2) + (y1'+y2)/z2^3
  207. *
  208. * For the special case x1=x2, y1=y2 (doubling) we have
  209. * lambda = 3/2 ((x2/z2^2)^2 + a) / (y2/z2^3)
  210. * = 3/2 (x2^2 + a*z2^4) / y2*z2)
  211. *
  212. * to get rid of fraction we write lambda as
  213. * lambda = r / (h*z2)
  214. * with r = is_doubling ? 3/2 x2^2 + az2^4 : (y1 - y2)
  215. * h = is_doubling ? y1+y2 : (x1 - x2)
  216. *
  217. * With z3 = h*z2 (the denominator of lambda)
  218. * we get x3 = lambda^2*z3^2 - (x1' + x2)/z2^2*z3^2
  219. * = r^2 - h^2 * (x1' + x2)
  220. * and y3 = 1/2 r * (2x3 - h^2*(x1' + x2)) + h^3*(y1' + y2)
  221. */
  222. /* h = x1 - x2
  223. * r = y1 - y2
  224. * x3 = r^2 - h^3 - 2*h^2*x2
  225. * y3 = r*(h^2*x2 - x3) - h^3*y2
  226. * z3 = h*z2
  227. */
  228. xz = p2->z;
  229. bn_multiply(&xz, &xz, prime); // xz = z2^2
  230. yz = p2->z;
  231. bn_multiply(&xz, &yz, prime); // yz = z2^3
  232. if (a != 0) {
  233. az = xz;
  234. bn_multiply(&az, &az, prime); // az = z2^4
  235. bn_mult_k(&az, -a, prime); // az = -az2^4
  236. }
  237. bn_multiply(&p1->x, &xz, prime); // xz = x1' = x1*z2^2;
  238. h = xz;
  239. bn_subtractmod(&h, &p2->x, &h, prime);
  240. bn_fast_mod(&h, prime);
  241. // h = x1' - x2;
  242. bn_add(&xz, &p2->x);
  243. // xz = x1' + x2
  244. // check for h == 0 % prime. Note that h never normalizes to
  245. // zero, since h = x1' + 2*prime - x2 > 0 and a positive
  246. // multiple of prime is always normalized to prime by
  247. // bn_fast_mod.
  248. is_doubling = bn_is_equal(&h, prime);
  249. bn_multiply(&p1->y, &yz, prime); // yz = y1' = y1*z2^3;
  250. bn_subtractmod(&yz, &p2->y, &r, prime);
  251. // r = y1' - y2;
  252. bn_add(&yz, &p2->y);
  253. // yz = y1' + y2
  254. r2 = p2->x;
  255. bn_multiply(&r2, &r2, prime);
  256. bn_mult_k(&r2, 3, prime);
  257. if (a != 0) {
  258. // subtract -a z2^4, i.e, add a z2^4
  259. bn_subtractmod(&r2, &az, &r2, prime);
  260. }
  261. bn_cmov(&r, is_doubling, &r2, &r);
  262. bn_cmov(&h, is_doubling, &yz, &h);
  263. // hsqx = h^2
  264. hsqx = h;
  265. bn_multiply(&hsqx, &hsqx, prime);
  266. // hcby = h^3
  267. hcby = h;
  268. bn_multiply(&hsqx, &hcby, prime);
  269. // hsqx = h^2 * (x1 + x2)
  270. bn_multiply(&xz, &hsqx, prime);
  271. // hcby = h^3 * (y1 + y2)
  272. bn_multiply(&yz, &hcby, prime);
  273. // z3 = h*z2
  274. bn_multiply(&h, &p2->z, prime);
  275. // x3 = r^2 - h^2 (x1 + x2)
  276. p2->x = r;
  277. bn_multiply(&p2->x, &p2->x, prime);
  278. bn_subtractmod(&p2->x, &hsqx, &p2->x, prime);
  279. bn_fast_mod(&p2->x, prime);
  280. // y3 = 1/2 (r*(h^2 (x1 + x2) - 2x3) - h^3 (y1 + y2))
  281. bn_subtractmod(&hsqx, &p2->x, &p2->y, prime);
  282. bn_subtractmod(&p2->y, &p2->x, &p2->y, prime);
  283. bn_multiply(&r, &p2->y, prime);
  284. bn_subtractmod(&p2->y, &hcby, &p2->y, prime);
  285. bn_mult_half(&p2->y, prime);
  286. bn_fast_mod(&p2->y, prime);
  287. }
  288. void point_jacobian_double(jacobian_curve_point *p, const ecdsa_curve *curve) {
  289. bignum256 az4 = {0}, m = {0}, msq = {0}, ysq = {0}, xysq = {0};
  290. const bignum256 *prime = &curve->prime;
  291. assert(-3 <= curve->a && curve->a <= 0);
  292. /* usual algorithm:
  293. *
  294. * lambda = (3((x/z^2)^2 + a) / 2y/z^3) = (3x^2 + az^4)/2yz
  295. * x3/z3^2 = lambda^2 - 2x/z^2
  296. * y3/z3^3 = lambda * (x/z^2 - x3/z3^2) - y/z^3
  297. *
  298. * to get rid of fraction we set
  299. * m = (3 x^2 + az^4) / 2
  300. * Hence,
  301. * lambda = m / yz = m / z3
  302. *
  303. * With z3 = yz (the denominator of lambda)
  304. * we get x3 = lambda^2*z3^2 - 2*x/z^2*z3^2
  305. * = m^2 - 2*xy^2
  306. * and y3 = (lambda * (x/z^2 - x3/z3^2) - y/z^3) * z3^3
  307. * = m * (xy^2 - x3) - y^4
  308. */
  309. /* m = (3*x^2 + a z^4) / 2
  310. * x3 = m^2 - 2*xy^2
  311. * y3 = m*(xy^2 - x3) - 8y^4
  312. * z3 = y*z
  313. */
  314. m = p->x;
  315. bn_multiply(&m, &m, prime);
  316. bn_mult_k(&m, 3, prime);
  317. az4 = p->z;
  318. bn_multiply(&az4, &az4, prime);
  319. bn_multiply(&az4, &az4, prime);
  320. bn_mult_k(&az4, -curve->a, prime);
  321. bn_subtractmod(&m, &az4, &m, prime);
  322. bn_mult_half(&m, prime);
  323. // msq = m^2
  324. msq = m;
  325. bn_multiply(&msq, &msq, prime);
  326. // ysq = y^2
  327. ysq = p->y;
  328. bn_multiply(&ysq, &ysq, prime);
  329. // xysq = xy^2
  330. xysq = p->x;
  331. bn_multiply(&ysq, &xysq, prime);
  332. // z3 = yz
  333. bn_multiply(&p->y, &p->z, prime);
  334. // x3 = m^2 - 2*xy^2
  335. p->x = xysq;
  336. bn_lshift(&p->x);
  337. bn_fast_mod(&p->x, prime);
  338. bn_subtractmod(&msq, &p->x, &p->x, prime);
  339. bn_fast_mod(&p->x, prime);
  340. // y3 = m*(xy^2 - x3) - y^4
  341. bn_subtractmod(&xysq, &p->x, &p->y, prime);
  342. bn_multiply(&m, &p->y, prime);
  343. bn_multiply(&ysq, &ysq, prime);
  344. bn_subtractmod(&p->y, &ysq, &p->y, prime);
  345. bn_fast_mod(&p->y, prime);
  346. }
  347. // res = k * p
  348. // returns 0 on success
  349. int point_multiply(const ecdsa_curve *curve, const bignum256 *k,
  350. const curve_point *p, curve_point *res) {
  351. // this algorithm is loosely based on
  352. // Katsuyuki Okeya and Tsuyoshi Takagi, The Width-w NAF Method Provides
  353. // Small Memory and Fast Elliptic Scalar Multiplications Secure against
  354. // Side Channel Attacks.
  355. if (!bn_is_less(k, &curve->order)) {
  356. return 1;
  357. }
  358. int i = 0, j = 0;
  359. static CONFIDENTIAL bignum256 a;
  360. uint32_t *aptr = NULL;
  361. uint32_t abits = 0;
  362. int ashift = 0;
  363. uint32_t is_even = (k->val[0] & 1) - 1;
  364. uint32_t bits = {0}, sign = {0}, nsign = {0};
  365. static CONFIDENTIAL jacobian_curve_point jres;
  366. curve_point pmult[8] = {0};
  367. const bignum256 *prime = &curve->prime;
  368. // is_even = 0xffffffff if k is even, 0 otherwise.
  369. // add 2^256.
  370. // make number odd: subtract curve->order if even
  371. uint32_t tmp = 1;
  372. uint32_t is_non_zero = 0;
  373. for (j = 0; j < 8; j++) {
  374. is_non_zero |= k->val[j];
  375. tmp += (BN_BASE - 1) + k->val[j] - (curve->order.val[j] & is_even);
  376. a.val[j] = tmp & (BN_BASE - 1);
  377. tmp >>= BN_BITS_PER_LIMB;
  378. }
  379. is_non_zero |= k->val[j];
  380. a.val[j] = tmp + 0xffffff + k->val[j] - (curve->order.val[j] & is_even);
  381. assert((a.val[0] & 1) != 0);
  382. // special case 0*p: just return zero. We don't care about constant time.
  383. if (!is_non_zero) {
  384. point_set_infinity(res);
  385. return 1;
  386. }
  387. // Now a = k + 2^256 (mod curve->order) and a is odd.
  388. //
  389. // The idea is to bring the new a into the form.
  390. // sum_{i=0..64} a[i] 16^i, where |a[i]| < 16 and a[i] is odd.
  391. // a[0] is odd, since a is odd. If a[i] would be even, we can
  392. // add 1 to it and subtract 16 from a[i-1]. Afterwards,
  393. // a[64] = 1, which is the 2^256 that we added before.
  394. //
  395. // Since k = a - 2^256 (mod curve->order), we can compute
  396. // k*p = sum_{i=0..63} a[i] 16^i * p
  397. //
  398. // We compute |a[i]| * p in advance for all possible
  399. // values of |a[i]| * p. pmult[i] = (2*i+1) * p
  400. // We compute p, 3*p, ..., 15*p and store it in the table pmult.
  401. // store p^2 temporarily in pmult[7]
  402. pmult[7] = *p;
  403. point_double(curve, &pmult[7]);
  404. // compute 3*p, etc by repeatedly adding p^2.
  405. pmult[0] = *p;
  406. for (i = 1; i < 8; i++) {
  407. pmult[i] = pmult[7];
  408. point_add(curve, &pmult[i - 1], &pmult[i]);
  409. }
  410. // now compute res = sum_{i=0..63} a[i] * 16^i * p step by step,
  411. // starting with i = 63.
  412. // initialize jres = |a[63]| * p.
  413. // Note that a[i] = a>>(4*i) & 0xf if (a&0x10) != 0
  414. // and - (16 - (a>>(4*i) & 0xf)) otherwise. We can compute this as
  415. // ((a ^ (((a >> 4) & 1) - 1)) & 0xf) >> 1
  416. // since a is odd.
  417. aptr = &a.val[8];
  418. abits = *aptr;
  419. ashift = 256 - (BN_BITS_PER_LIMB * 8) - 4;
  420. bits = abits >> ashift;
  421. sign = (bits >> 4) - 1;
  422. bits ^= sign;
  423. bits &= 15;
  424. curve_to_jacobian(&pmult[bits >> 1], &jres, prime);
  425. for (i = 62; i >= 0; i--) {
  426. // sign = sign(a[i+1]) (0xffffffff for negative, 0 for positive)
  427. // invariant jres = (-1)^sign sum_{j=i+1..63} (a[j] * 16^{j-i-1} * p)
  428. // abits >> (ashift - 4) = lowbits(a >> (i*4))
  429. point_jacobian_double(&jres, curve);
  430. point_jacobian_double(&jres, curve);
  431. point_jacobian_double(&jres, curve);
  432. point_jacobian_double(&jres, curve);
  433. // get lowest 5 bits of a >> (i*4).
  434. ashift -= 4;
  435. if (ashift < 0) {
  436. // the condition only depends on the iteration number and
  437. // leaks no private information to a side-channel.
  438. bits = abits << (-ashift);
  439. abits = *(--aptr);
  440. ashift += BN_BITS_PER_LIMB;
  441. bits |= abits >> ashift;
  442. } else {
  443. bits = abits >> ashift;
  444. }
  445. bits &= 31;
  446. nsign = (bits >> 4) - 1;
  447. bits ^= nsign;
  448. bits &= 15;
  449. // negate last result to make signs of this round and the
  450. // last round equal.
  451. bn_cnegate((sign ^ nsign) & 1, &jres.z, prime);
  452. // add odd factor
  453. point_jacobian_add(&pmult[bits >> 1], &jres, curve);
  454. sign = nsign;
  455. }
  456. bn_cnegate(sign & 1, &jres.z, prime);
  457. jacobian_to_curve(&jres, res, prime);
  458. memzero(&a, sizeof(a));
  459. memzero(&jres, sizeof(jres));
  460. return 0;
  461. }
  462. #if USE_PRECOMPUTED_CP
  463. // res = k * G
  464. // k must be a normalized number with 0 <= k < curve->order
  465. // returns 0 on success
  466. int scalar_multiply(const ecdsa_curve *curve, const bignum256 *k,
  467. curve_point *res) {
  468. if (!bn_is_less(k, &curve->order)) {
  469. return 1;
  470. }
  471. int i = {0}, j = {0};
  472. static CONFIDENTIAL bignum256 a;
  473. uint32_t is_even = (k->val[0] & 1) - 1;
  474. uint32_t lowbits = 0;
  475. static CONFIDENTIAL jacobian_curve_point jres;
  476. const bignum256 *prime = &curve->prime;
  477. // is_even = 0xffffffff if k is even, 0 otherwise.
  478. // add 2^256.
  479. // make number odd: subtract curve->order if even
  480. uint32_t tmp = 1;
  481. uint32_t is_non_zero = 0;
  482. for (j = 0; j < 8; j++) {
  483. is_non_zero |= k->val[j];
  484. tmp += (BN_BASE - 1) + k->val[j] - (curve->order.val[j] & is_even);
  485. a.val[j] = tmp & (BN_BASE - 1);
  486. tmp >>= BN_BITS_PER_LIMB;
  487. }
  488. is_non_zero |= k->val[j];
  489. a.val[j] = tmp + 0xffffff + k->val[j] - (curve->order.val[j] & is_even);
  490. assert((a.val[0] & 1) != 0);
  491. // special case 0*G: just return zero. We don't care about constant time.
  492. if (!is_non_zero) {
  493. point_set_infinity(res);
  494. return 0;
  495. }
  496. // Now a = k + 2^256 (mod curve->order) and a is odd.
  497. //
  498. // The idea is to bring the new a into the form.
  499. // sum_{i=0..64} a[i] 16^i, where |a[i]| < 16 and a[i] is odd.
  500. // a[0] is odd, since a is odd. If a[i] would be even, we can
  501. // add 1 to it and subtract 16 from a[i-1]. Afterwards,
  502. // a[64] = 1, which is the 2^256 that we added before.
  503. //
  504. // Since k = a - 2^256 (mod curve->order), we can compute
  505. // k*G = sum_{i=0..63} a[i] 16^i * G
  506. //
  507. // We have a big table curve->cp that stores all possible
  508. // values of |a[i]| 16^i * G.
  509. // curve->cp[i][j] = (2*j+1) * 16^i * G
  510. // now compute res = sum_{i=0..63} a[i] * 16^i * G step by step.
  511. // initial res = |a[0]| * G. Note that a[0] = a & 0xf if (a&0x10) != 0
  512. // and - (16 - (a & 0xf)) otherwise. We can compute this as
  513. // ((a ^ (((a >> 4) & 1) - 1)) & 0xf) >> 1
  514. // since a is odd.
  515. lowbits = a.val[0] & ((1 << 5) - 1);
  516. lowbits ^= (lowbits >> 4) - 1;
  517. lowbits &= 15;
  518. curve_to_jacobian(&curve->cp[0][lowbits >> 1], &jres, prime);
  519. for (i = 1; i < 64; i++) {
  520. // invariant res = sign(a[i-1]) sum_{j=0..i-1} (a[j] * 16^j * G)
  521. // shift a by 4 places.
  522. for (j = 0; j < 8; j++) {
  523. a.val[j] =
  524. (a.val[j] >> 4) | ((a.val[j + 1] & 0xf) << (BN_BITS_PER_LIMB - 4));
  525. }
  526. a.val[j] >>= 4;
  527. // a = old(a)>>(4*i)
  528. // a is even iff sign(a[i-1]) = -1
  529. lowbits = a.val[0] & ((1 << 5) - 1);
  530. lowbits ^= (lowbits >> 4) - 1;
  531. lowbits &= 15;
  532. // negate last result to make signs of this round and the
  533. // last round equal.
  534. bn_cnegate(~lowbits & 1, &jres.y, prime);
  535. // add odd factor
  536. point_jacobian_add(&curve->cp[i][lowbits >> 1], &jres, curve);
  537. }
  538. bn_cnegate(~(a.val[0] >> 4) & 1, &jres.y, prime);
  539. jacobian_to_curve(&jres, res, prime);
  540. memzero(&a, sizeof(a));
  541. memzero(&jres, sizeof(jres));
  542. return 0;
  543. }
  544. #else
  545. int scalar_multiply(const ecdsa_curve *curve, const bignum256 *k,
  546. curve_point *res) {
  547. return point_multiply(curve, k, &curve->G, res);
  548. }
  549. #endif
  550. int ecdh_multiply(const ecdsa_curve *curve, const uint8_t *priv_key,
  551. const uint8_t *pub_key, uint8_t *session_key) {
  552. curve_point point = {0};
  553. if (!ecdsa_read_pubkey(curve, pub_key, &point)) {
  554. return 1;
  555. }
  556. bignum256 k = {0};
  557. bn_read_be(priv_key, &k);
  558. if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
  559. // Invalid private key.
  560. return 2;
  561. }
  562. point_multiply(curve, &k, &point, &point);
  563. memzero(&k, sizeof(k));
  564. session_key[0] = 0x04;
  565. bn_write_be(&point.x, session_key + 1);
  566. bn_write_be(&point.y, session_key + 33);
  567. memzero(&point, sizeof(point));
  568. return 0;
  569. }
  570. // msg is a data to be signed
  571. // msg_len is the message length
  572. int ecdsa_sign(const ecdsa_curve *curve, HasherType hasher_sign,
  573. const uint8_t *priv_key, const uint8_t *msg, uint32_t msg_len,
  574. uint8_t *sig, uint8_t *pby,
  575. int (*is_canonical)(uint8_t by, uint8_t sig[64])) {
  576. uint8_t hash[32] = {0};
  577. hasher_Raw(hasher_sign, msg, msg_len, hash);
  578. int res = ecdsa_sign_digest(curve, priv_key, hash, sig, pby, is_canonical);
  579. memzero(hash, sizeof(hash));
  580. return res;
  581. }
  582. // uses secp256k1 curve
  583. // priv_key is a 32 byte big endian stored number
  584. // sig is 64 bytes long array for the signature
  585. // digest is 32 bytes of digest
  586. // is_canonical is an optional function that checks if the signature
  587. // conforms to additional coin-specific rules.
  588. int ecdsa_sign_digest(const ecdsa_curve *curve, const uint8_t *priv_key,
  589. const uint8_t *digest, uint8_t *sig, uint8_t *pby,
  590. int (*is_canonical)(uint8_t by, uint8_t sig[64])) {
  591. int i = 0;
  592. curve_point R = {0};
  593. bignum256 k = {0}, z = {0}, randk = {0};
  594. bignum256 *s = &R.y;
  595. uint8_t by; // signature recovery byte
  596. #if USE_RFC6979
  597. rfc6979_state rng = {0};
  598. init_rfc6979(priv_key, digest, curve, &rng);
  599. #endif
  600. bn_read_be(digest, &z);
  601. if (bn_is_zero(&z)) {
  602. // The probability of the digest being all-zero by chance is infinitesimal,
  603. // so this is most likely an indication of a bug. Furthermore, the signature
  604. // has no value, because in this case it can be easily forged for any public
  605. // key, see ecdsa_verify_digest().
  606. return 1;
  607. }
  608. for (i = 0; i < 10000; i++) {
  609. #if USE_RFC6979
  610. // generate K deterministically
  611. generate_k_rfc6979(&k, &rng);
  612. // if k is too big or too small, we don't like it
  613. if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
  614. continue;
  615. }
  616. #else
  617. // generate random number k
  618. generate_k_random(&k, &curve->order);
  619. #endif
  620. // compute k*G
  621. scalar_multiply(curve, &k, &R);
  622. by = R.y.val[0] & 1;
  623. // r = (rx mod n)
  624. if (!bn_is_less(&R.x, &curve->order)) {
  625. bn_subtract(&R.x, &curve->order, &R.x);
  626. by |= 2;
  627. }
  628. // if r is zero, we retry
  629. if (bn_is_zero(&R.x)) {
  630. continue;
  631. }
  632. bn_read_be(priv_key, s);
  633. if (bn_is_zero(s) || !bn_is_less(s, &curve->order)) {
  634. // Invalid private key.
  635. return 2;
  636. }
  637. // randomize operations to counter side-channel attacks
  638. generate_k_random(&randk, &curve->order);
  639. bn_multiply(&randk, &k, &curve->order); // k*rand
  640. bn_inverse(&k, &curve->order); // (k*rand)^-1
  641. bn_multiply(&R.x, s, &curve->order); // R.x*priv
  642. bn_add(s, &z); // R.x*priv + z
  643. bn_multiply(&k, s, &curve->order); // (k*rand)^-1 (R.x*priv + z)
  644. bn_multiply(&randk, s, &curve->order); // k^-1 (R.x*priv + z)
  645. bn_mod(s, &curve->order);
  646. // if s is zero, we retry
  647. if (bn_is_zero(s)) {
  648. continue;
  649. }
  650. // if S > order/2 => S = -S
  651. if (bn_is_less(&curve->order_half, s)) {
  652. bn_subtract(&curve->order, s, s);
  653. by ^= 1;
  654. }
  655. // we are done, R.x and s is the result signature
  656. bn_write_be(&R.x, sig);
  657. bn_write_be(s, sig + 32);
  658. // check if the signature is acceptable or retry
  659. if (is_canonical && !is_canonical(by, sig)) {
  660. continue;
  661. }
  662. if (pby) {
  663. *pby = by;
  664. }
  665. memzero(&k, sizeof(k));
  666. memzero(&randk, sizeof(randk));
  667. #if USE_RFC6979
  668. memzero(&rng, sizeof(rng));
  669. #endif
  670. return 0;
  671. }
  672. // Too many retries without a valid signature
  673. // -> fail with an error
  674. memzero(&k, sizeof(k));
  675. memzero(&randk, sizeof(randk));
  676. #if USE_RFC6979
  677. memzero(&rng, sizeof(rng));
  678. #endif
  679. return -1;
  680. }
  681. // returns 0 on success
  682. int ecdsa_get_public_key33(const ecdsa_curve *curve, const uint8_t *priv_key,
  683. uint8_t *pub_key) {
  684. curve_point R = {0};
  685. bignum256 k = {0};
  686. bn_read_be(priv_key, &k);
  687. if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
  688. // Invalid private key.
  689. memzero(pub_key, 33);
  690. return -1;
  691. }
  692. // compute k*G
  693. if (scalar_multiply(curve, &k, &R) != 0) {
  694. memzero(&k, sizeof(k));
  695. return 1;
  696. }
  697. pub_key[0] = 0x02 | (R.y.val[0] & 0x01);
  698. bn_write_be(&R.x, pub_key + 1);
  699. memzero(&R, sizeof(R));
  700. memzero(&k, sizeof(k));
  701. return 0;
  702. }
  703. // returns 0 on success
  704. int ecdsa_get_public_key65(const ecdsa_curve *curve, const uint8_t *priv_key,
  705. uint8_t *pub_key) {
  706. curve_point R = {0};
  707. bignum256 k = {0};
  708. bn_read_be(priv_key, &k);
  709. if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
  710. // Invalid private key.
  711. memzero(pub_key, 65);
  712. return -1;
  713. }
  714. // compute k*G
  715. if (scalar_multiply(curve, &k, &R) != 0) {
  716. memzero(&k, sizeof(k));
  717. return 1;
  718. }
  719. pub_key[0] = 0x04;
  720. bn_write_be(&R.x, pub_key + 1);
  721. bn_write_be(&R.y, pub_key + 33);
  722. memzero(&R, sizeof(R));
  723. memzero(&k, sizeof(k));
  724. return 0;
  725. }
  726. int ecdsa_uncompress_pubkey(const ecdsa_curve *curve, const uint8_t *pub_key,
  727. uint8_t *uncompressed) {
  728. curve_point pub = {0};
  729. if (!ecdsa_read_pubkey(curve, pub_key, &pub)) {
  730. return 0;
  731. }
  732. uncompressed[0] = 4;
  733. bn_write_be(&pub.x, uncompressed + 1);
  734. bn_write_be(&pub.y, uncompressed + 33);
  735. return 1;
  736. }
  737. void ecdsa_get_pubkeyhash(const uint8_t *pub_key, HasherType hasher_pubkey,
  738. uint8_t *pubkeyhash) {
  739. uint8_t h[HASHER_DIGEST_LENGTH] = {0};
  740. if (pub_key[0] == 0x04) { // uncompressed format
  741. hasher_Raw(hasher_pubkey, pub_key, 65, h);
  742. } else if (pub_key[0] == 0x00) { // point at infinity
  743. hasher_Raw(hasher_pubkey, pub_key, 1, h);
  744. } else { // expecting compressed format
  745. hasher_Raw(hasher_pubkey, pub_key, 33, h);
  746. }
  747. memcpy(pubkeyhash, h, 20);
  748. memzero(h, sizeof(h));
  749. }
  750. void ecdsa_get_address_raw(const uint8_t *pub_key, uint32_t version,
  751. HasherType hasher_pubkey, uint8_t *addr_raw) {
  752. size_t prefix_len = address_prefix_bytes_len(version);
  753. address_write_prefix_bytes(version, addr_raw);
  754. ecdsa_get_pubkeyhash(pub_key, hasher_pubkey, addr_raw + prefix_len);
  755. }
  756. void ecdsa_get_address(const uint8_t *pub_key, uint32_t version,
  757. HasherType hasher_pubkey, HasherType hasher_base58,
  758. char *addr, int addrsize) {
  759. uint8_t raw[MAX_ADDR_RAW_SIZE] = {0};
  760. size_t prefix_len = address_prefix_bytes_len(version);
  761. ecdsa_get_address_raw(pub_key, version, hasher_pubkey, raw);
  762. base58_encode_check(raw, 20 + prefix_len, hasher_base58, addr, addrsize);
  763. // not as important to clear this one, but we might as well
  764. memzero(raw, sizeof(raw));
  765. }
  766. void ecdsa_get_address_segwit_p2sh_raw(const uint8_t *pub_key, uint32_t version,
  767. HasherType hasher_pubkey,
  768. uint8_t *addr_raw) {
  769. uint8_t buf[32 + 2] = {0};
  770. buf[0] = 0; // version byte
  771. buf[1] = 20; // push 20 bytes
  772. ecdsa_get_pubkeyhash(pub_key, hasher_pubkey, buf + 2);
  773. size_t prefix_len = address_prefix_bytes_len(version);
  774. address_write_prefix_bytes(version, addr_raw);
  775. hasher_Raw(hasher_pubkey, buf, 22, addr_raw + prefix_len);
  776. }
  777. void ecdsa_get_address_segwit_p2sh(const uint8_t *pub_key, uint32_t version,
  778. HasherType hasher_pubkey,
  779. HasherType hasher_base58, char *addr,
  780. int addrsize) {
  781. uint8_t raw[MAX_ADDR_RAW_SIZE] = {0};
  782. size_t prefix_len = address_prefix_bytes_len(version);
  783. ecdsa_get_address_segwit_p2sh_raw(pub_key, version, hasher_pubkey, raw);
  784. base58_encode_check(raw, prefix_len + 20, hasher_base58, addr, addrsize);
  785. memzero(raw, sizeof(raw));
  786. }
  787. void ecdsa_get_wif(const uint8_t *priv_key, uint32_t version,
  788. HasherType hasher_base58, char *wif, int wifsize) {
  789. uint8_t wif_raw[MAX_WIF_RAW_SIZE] = {0};
  790. size_t prefix_len = address_prefix_bytes_len(version);
  791. address_write_prefix_bytes(version, wif_raw);
  792. memcpy(wif_raw + prefix_len, priv_key, 32);
  793. wif_raw[prefix_len + 32] = 0x01;
  794. base58_encode_check(wif_raw, prefix_len + 32 + 1, hasher_base58, wif,
  795. wifsize);
  796. // private keys running around our stack can cause trouble
  797. memzero(wif_raw, sizeof(wif_raw));
  798. }
  799. int ecdsa_address_decode(const char *addr, uint32_t version,
  800. HasherType hasher_base58, uint8_t *out) {
  801. if (!addr) return 0;
  802. int prefix_len = address_prefix_bytes_len(version);
  803. return base58_decode_check(addr, hasher_base58, out, 20 + prefix_len) ==
  804. 20 + prefix_len &&
  805. address_check_prefix(out, version);
  806. }
  807. void compress_coords(const curve_point *cp, uint8_t *compressed) {
  808. compressed[0] = bn_is_odd(&cp->y) ? 0x03 : 0x02;
  809. bn_write_be(&cp->x, compressed + 1);
  810. }
  811. void uncompress_coords(const ecdsa_curve *curve, uint8_t odd,
  812. const bignum256 *x, bignum256 *y) {
  813. // y^2 = x^3 + a*x + b
  814. memcpy(y, x, sizeof(bignum256)); // y is x
  815. bn_multiply(x, y, &curve->prime); // y is x^2
  816. bn_subi(y, -curve->a, &curve->prime); // y is x^2 + a
  817. bn_multiply(x, y, &curve->prime); // y is x^3 + ax
  818. bn_add(y, &curve->b); // y is x^3 + ax + b
  819. bn_sqrt(y, &curve->prime); // y = sqrt(y)
  820. if ((odd & 0x01) != (y->val[0] & 1)) {
  821. bn_subtract(&curve->prime, y, y); // y = -y
  822. }
  823. }
  824. int ecdsa_read_pubkey(const ecdsa_curve *curve, const uint8_t *pub_key,
  825. curve_point *pub) {
  826. if (!curve) {
  827. curve = &secp256k1;
  828. }
  829. if (pub_key[0] == 0x04) {
  830. bn_read_be(pub_key + 1, &(pub->x));
  831. bn_read_be(pub_key + 33, &(pub->y));
  832. return ecdsa_validate_pubkey(curve, pub);
  833. }
  834. if (pub_key[0] == 0x02 || pub_key[0] == 0x03) { // compute missing y coords
  835. bn_read_be(pub_key + 1, &(pub->x));
  836. uncompress_coords(curve, pub_key[0], &(pub->x), &(pub->y));
  837. return ecdsa_validate_pubkey(curve, pub);
  838. }
  839. // error
  840. return 0;
  841. }
  842. // Verifies that:
  843. // - pub is not the point at infinity.
  844. // - pub->x and pub->y are in range [0,p-1].
  845. // - pub is on the curve.
  846. // We assume that all curves using this code have cofactor 1, so there is no
  847. // need to verify that pub is a scalar multiple of G.
  848. int ecdsa_validate_pubkey(const ecdsa_curve *curve, const curve_point *pub) {
  849. bignum256 y_2 = {0}, x3_ax_b = {0};
  850. if (point_is_infinity(pub)) {
  851. return 0;
  852. }
  853. if (!bn_is_less(&(pub->x), &curve->prime) ||
  854. !bn_is_less(&(pub->y), &curve->prime)) {
  855. return 0;
  856. }
  857. memcpy(&y_2, &(pub->y), sizeof(bignum256));
  858. memcpy(&x3_ax_b, &(pub->x), sizeof(bignum256));
  859. // y^2
  860. bn_multiply(&(pub->y), &y_2, &curve->prime);
  861. bn_mod(&y_2, &curve->prime);
  862. // x^3 + ax + b
  863. bn_multiply(&(pub->x), &x3_ax_b, &curve->prime); // x^2
  864. bn_subi(&x3_ax_b, -curve->a, &curve->prime); // x^2 + a
  865. bn_multiply(&(pub->x), &x3_ax_b, &curve->prime); // x^3 + ax
  866. bn_addmod(&x3_ax_b, &curve->b, &curve->prime); // x^3 + ax + b
  867. bn_mod(&x3_ax_b, &curve->prime);
  868. if (!bn_is_equal(&x3_ax_b, &y_2)) {
  869. return 0;
  870. }
  871. return 1;
  872. }
  873. // uses secp256k1 curve
  874. // pub_key - 65 bytes uncompressed key
  875. // signature - 64 bytes signature
  876. // msg is a data that was signed
  877. // msg_len is the message length
  878. int ecdsa_verify(const ecdsa_curve *curve, HasherType hasher_sign,
  879. const uint8_t *pub_key, const uint8_t *sig, const uint8_t *msg,
  880. uint32_t msg_len) {
  881. uint8_t hash[32] = {0};
  882. hasher_Raw(hasher_sign, msg, msg_len, hash);
  883. int res = ecdsa_verify_digest(curve, pub_key, sig, hash);
  884. memzero(hash, sizeof(hash));
  885. return res;
  886. }
  887. // Compute public key from signature and recovery id.
  888. // returns 0 if the key is successfully recovered
  889. int ecdsa_recover_pub_from_sig(const ecdsa_curve *curve, uint8_t *pub_key,
  890. const uint8_t *sig, const uint8_t *digest,
  891. int recid) {
  892. bignum256 r = {0}, s = {0}, e = {0};
  893. curve_point cp = {0}, cp2 = {0};
  894. // read r and s
  895. bn_read_be(sig, &r);
  896. bn_read_be(sig + 32, &s);
  897. if (!bn_is_less(&r, &curve->order) || bn_is_zero(&r)) {
  898. return 1;
  899. }
  900. if (!bn_is_less(&s, &curve->order) || bn_is_zero(&s)) {
  901. return 1;
  902. }
  903. // cp = R = k * G (k is secret nonce when signing)
  904. memcpy(&cp.x, &r, sizeof(bignum256));
  905. if (recid & 2) {
  906. bn_add(&cp.x, &curve->order);
  907. if (!bn_is_less(&cp.x, &curve->prime)) {
  908. return 1;
  909. }
  910. }
  911. // compute y from x
  912. uncompress_coords(curve, recid & 1, &cp.x, &cp.y);
  913. if (!ecdsa_validate_pubkey(curve, &cp)) {
  914. return 1;
  915. }
  916. // e = -digest
  917. bn_read_be(digest, &e);
  918. bn_mod(&e, &curve->order);
  919. bn_subtract(&curve->order, &e, &e);
  920. // r = r^-1
  921. bn_inverse(&r, &curve->order);
  922. // e = -digest * r^-1
  923. bn_multiply(&r, &e, &curve->order);
  924. bn_mod(&e, &curve->order);
  925. // s = s * r^-1
  926. bn_multiply(&r, &s, &curve->order);
  927. bn_mod(&s, &curve->order);
  928. // cp = s * r^-1 * k * G
  929. point_multiply(curve, &s, &cp, &cp);
  930. // cp2 = -digest * r^-1 * G
  931. scalar_multiply(curve, &e, &cp2);
  932. // cp = (s * r^-1 * k - digest * r^-1) * G = Pub
  933. point_add(curve, &cp2, &cp);
  934. // The point at infinity is not considered to be a valid public key.
  935. if (point_is_infinity(&cp)) {
  936. return 1;
  937. }
  938. pub_key[0] = 0x04;
  939. bn_write_be(&cp.x, pub_key + 1);
  940. bn_write_be(&cp.y, pub_key + 33);
  941. return 0;
  942. }
  943. // returns 0 if verification succeeded
  944. int ecdsa_verify_digest(const ecdsa_curve *curve, const uint8_t *pub_key,
  945. const uint8_t *sig, const uint8_t *digest) {
  946. curve_point pub = {0}, res = {0};
  947. bignum256 r = {0}, s = {0}, z = {0};
  948. int result = 0;
  949. if (!ecdsa_read_pubkey(curve, pub_key, &pub)) {
  950. result = 1;
  951. }
  952. if (result == 0) {
  953. bn_read_be(sig, &r);
  954. bn_read_be(sig + 32, &s);
  955. bn_read_be(digest, &z);
  956. if (bn_is_zero(&r) || bn_is_zero(&s) || (!bn_is_less(&r, &curve->order)) ||
  957. (!bn_is_less(&s, &curve->order))) {
  958. result = 2;
  959. }
  960. if (bn_is_zero(&z)) {
  961. // The digest was all-zero. The probability of this happening by chance is
  962. // infinitesimal, but it could be induced by a fault injection. In this
  963. // case the signature (r,s) can be forged by taking r := (t * Q).x mod n
  964. // and s := r * t^-1 mod n for any t in [1, n-1]. We fail verification,
  965. // because there is no guarantee that the signature was created by the
  966. // owner of the private key.
  967. result = 3;
  968. }
  969. }
  970. if (result == 0) {
  971. bn_inverse(&s, &curve->order); // s = s^-1
  972. bn_multiply(&s, &z, &curve->order); // z = z * s [u1 = z * s^-1 mod n]
  973. bn_mod(&z, &curve->order);
  974. }
  975. if (result == 0) {
  976. bn_multiply(&r, &s, &curve->order); // s = r * s [u2 = r * s^-1 mod n]
  977. bn_mod(&s, &curve->order);
  978. scalar_multiply(curve, &z, &res); // res = z * G [= u1 * G]
  979. point_multiply(curve, &s, &pub, &pub); // pub = s * pub [= u2 * Q]
  980. point_add(curve, &pub, &res); // res = pub + res [R = u1 * G + u2 * Q]
  981. if (point_is_infinity(&res)) {
  982. // R == Infinity
  983. result = 4;
  984. }
  985. }
  986. if (result == 0) {
  987. bn_mod(&(res.x), &curve->order);
  988. if (!bn_is_equal(&res.x, &r)) {
  989. // R.x != r
  990. // signature does not match
  991. result = 5;
  992. }
  993. }
  994. memzero(&pub, sizeof(pub));
  995. memzero(&res, sizeof(res));
  996. memzero(&r, sizeof(r));
  997. memzero(&s, sizeof(s));
  998. memzero(&z, sizeof(z));
  999. // all OK
  1000. return result;
  1001. }
  1002. int ecdsa_sig_to_der(const uint8_t *sig, uint8_t *der) {
  1003. int i = 0;
  1004. uint8_t *p = der, *len = NULL, *len1 = NULL, *len2 = NULL;
  1005. *p = 0x30;
  1006. p++; // sequence
  1007. *p = 0x00;
  1008. len = p;
  1009. p++; // len(sequence)
  1010. *p = 0x02;
  1011. p++; // integer
  1012. *p = 0x00;
  1013. len1 = p;
  1014. p++; // len(integer)
  1015. // process R
  1016. i = 0;
  1017. while (i < 31 && sig[i] == 0) {
  1018. i++;
  1019. } // skip leading zeroes
  1020. if (sig[i] >= 0x80) { // put zero in output if MSB set
  1021. *p = 0x00;
  1022. p++;
  1023. *len1 = *len1 + 1;
  1024. }
  1025. while (i < 32) { // copy bytes to output
  1026. *p = sig[i];
  1027. p++;
  1028. *len1 = *len1 + 1;
  1029. i++;
  1030. }
  1031. *p = 0x02;
  1032. p++; // integer
  1033. *p = 0x00;
  1034. len2 = p;
  1035. p++; // len(integer)
  1036. // process S
  1037. i = 32;
  1038. while (i < 63 && sig[i] == 0) {
  1039. i++;
  1040. } // skip leading zeroes
  1041. if (sig[i] >= 0x80) { // put zero in output if MSB set
  1042. *p = 0x00;
  1043. p++;
  1044. *len2 = *len2 + 1;
  1045. }
  1046. while (i < 64) { // copy bytes to output
  1047. *p = sig[i];
  1048. p++;
  1049. *len2 = *len2 + 1;
  1050. i++;
  1051. }
  1052. *len = *len1 + *len2 + 4;
  1053. return *len + 2;
  1054. }
  1055. // Parse a DER-encoded signature. We don't check whether the encoded integers
  1056. // satisfy DER requirements regarding leading zeros.
  1057. int ecdsa_sig_from_der(const uint8_t *der, size_t der_len, uint8_t sig[64]) {
  1058. memzero(sig, 64);
  1059. // Check sequence header.
  1060. if (der_len < 2 || der_len > 72 || der[0] != 0x30 || der[1] != der_len - 2) {
  1061. return 1;
  1062. }
  1063. // Read two DER-encoded integers.
  1064. size_t pos = 2;
  1065. for (int i = 0; i < 2; ++i) {
  1066. // Check integer header.
  1067. if (der_len < pos + 2 || der[pos] != 0x02) {
  1068. return 1;
  1069. }
  1070. // Locate the integer.
  1071. size_t int_len = der[pos + 1];
  1072. pos += 2;
  1073. if (pos + int_len > der_len) {
  1074. return 1;
  1075. }
  1076. // Skip a possible leading zero.
  1077. if (int_len != 0 && der[pos] == 0) {
  1078. int_len--;
  1079. pos++;
  1080. }
  1081. // Copy the integer to the output, making sure it fits.
  1082. if (int_len > 32) {
  1083. return 1;
  1084. }
  1085. memcpy(sig + 32 * (i + 1) - int_len, der + pos, int_len);
  1086. // Move on to the next one.
  1087. pos += int_len;
  1088. }
  1089. // Check that there are no trailing elements in the sequence.
  1090. if (pos != der_len) {
  1091. return 1;
  1092. }
  1093. return 0;
  1094. }