ecdsa.c 37 KB

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