monocypher.c 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956
  1. // Monocypher version 4.0.2
  2. //
  3. // This file is dual-licensed. Choose whichever licence you want from
  4. // the two licences listed below.
  5. //
  6. // The first licence is a regular 2-clause BSD licence. The second licence
  7. // is the CC-0 from Creative Commons. It is intended to release Monocypher
  8. // to the public domain. The BSD licence serves as a fallback option.
  9. //
  10. // SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
  11. //
  12. // ------------------------------------------------------------------------
  13. //
  14. // Copyright (c) 2017-2020, Loup Vaillant
  15. // All rights reserved.
  16. //
  17. //
  18. // Redistribution and use in source and binary forms, with or without
  19. // modification, are permitted provided that the following conditions are
  20. // met:
  21. //
  22. // 1. Redistributions of source code must retain the above copyright
  23. // notice, this list of conditions and the following disclaimer.
  24. //
  25. // 2. Redistributions in binary form must reproduce the above copyright
  26. // notice, this list of conditions and the following disclaimer in the
  27. // documentation and/or other materials provided with the
  28. // distribution.
  29. //
  30. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  31. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  32. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  33. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  34. // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  36. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  37. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  38. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  39. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  40. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41. //
  42. // ------------------------------------------------------------------------
  43. //
  44. // Written in 2017-2020 by Loup Vaillant
  45. //
  46. // To the extent possible under law, the author(s) have dedicated all copyright
  47. // and related neighboring rights to this software to the public domain
  48. // worldwide. This software is distributed without any warranty.
  49. //
  50. // You should have received a copy of the CC0 Public Domain Dedication along
  51. // with this software. If not, see
  52. // <https://creativecommons.org/publicdomain/zero/1.0/>
  53. #include "monocypher.h"
  54. #ifdef MONOCYPHER_CPP_NAMESPACE
  55. namespace MONOCYPHER_CPP_NAMESPACE {
  56. #endif
  57. /////////////////
  58. /// Utilities ///
  59. /////////////////
  60. #define FOR_T(type, i, start, end) for (type i = (start); i < (end); i++)
  61. #define FOR(i, start, end) FOR_T(size_t, i, start, end)
  62. #define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_]
  63. #define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0
  64. #define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx)))
  65. #define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer))
  66. #define MIN(a, b) ((a) <= (b) ? (a) : (b))
  67. #define MAX(a, b) ((a) >= (b) ? (a) : (b))
  68. typedef int8_t i8;
  69. typedef uint8_t u8;
  70. typedef int16_t i16;
  71. typedef uint32_t u32;
  72. typedef int32_t i32;
  73. typedef int64_t i64;
  74. typedef uint64_t u64;
  75. static const u8 zero[128] = {0};
  76. // returns the smallest positive integer y such that
  77. // (x + y) % pow_2 == 0
  78. // Basically, y is the "gap" missing to align x.
  79. // Only works when pow_2 is a power of 2.
  80. // Note: we use ~x+1 instead of -x to avoid compiler warnings
  81. static size_t gap(size_t x, size_t pow_2)
  82. {
  83. return (~x + 1) & (pow_2 - 1);
  84. }
  85. static u32 load24_le(const u8 s[3])
  86. {
  87. return
  88. ((u32)s[0] << 0) |
  89. ((u32)s[1] << 8) |
  90. ((u32)s[2] << 16);
  91. }
  92. static u32 load32_le(const u8 s[4])
  93. {
  94. return
  95. ((u32)s[0] << 0) |
  96. ((u32)s[1] << 8) |
  97. ((u32)s[2] << 16) |
  98. ((u32)s[3] << 24);
  99. }
  100. static u64 load64_le(const u8 s[8])
  101. {
  102. return load32_le(s) | ((u64)load32_le(s+4) << 32);
  103. }
  104. static void store32_le(u8 out[4], u32 in)
  105. {
  106. out[0] = in & 0xff;
  107. out[1] = (in >> 8) & 0xff;
  108. out[2] = (in >> 16) & 0xff;
  109. out[3] = (in >> 24) & 0xff;
  110. }
  111. static void store64_le(u8 out[8], u64 in)
  112. {
  113. store32_le(out , (u32)in );
  114. store32_le(out + 4, in >> 32);
  115. }
  116. static void load32_le_buf (u32 *dst, const u8 *src, size_t size) {
  117. FOR(i, 0, size) { dst[i] = load32_le(src + i*4); }
  118. }
  119. static void load64_le_buf (u64 *dst, const u8 *src, size_t size) {
  120. FOR(i, 0, size) { dst[i] = load64_le(src + i*8); }
  121. }
  122. static void store32_le_buf(u8 *dst, const u32 *src, size_t size) {
  123. FOR(i, 0, size) { store32_le(dst + i*4, src[i]); }
  124. }
  125. static void store64_le_buf(u8 *dst, const u64 *src, size_t size) {
  126. FOR(i, 0, size) { store64_le(dst + i*8, src[i]); }
  127. }
  128. static u64 rotr64(u64 x, u64 n) { return (x >> n) ^ (x << (64 - n)); }
  129. static u32 rotl32(u32 x, u32 n) { return (x << n) ^ (x >> (32 - n)); }
  130. static int neq0(u64 diff)
  131. {
  132. // constant time comparison to zero
  133. // return diff != 0 ? -1 : 0
  134. u64 half = (diff >> 32) | ((u32)diff);
  135. return (1 & ((half - 1) >> 32)) - 1;
  136. }
  137. static u64 x16(const u8 a[16], const u8 b[16])
  138. {
  139. return (load64_le(a + 0) ^ load64_le(b + 0))
  140. | (load64_le(a + 8) ^ load64_le(b + 8));
  141. }
  142. static u64 x32(const u8 a[32],const u8 b[32]){return x16(a,b)| x16(a+16, b+16);}
  143. static u64 x64(const u8 a[64],const u8 b[64]){return x32(a,b)| x32(a+32, b+32);}
  144. int crypto_verify16(const u8 a[16], const u8 b[16]){ return neq0(x16(a, b)); }
  145. int crypto_verify32(const u8 a[32], const u8 b[32]){ return neq0(x32(a, b)); }
  146. int crypto_verify64(const u8 a[64], const u8 b[64]){ return neq0(x64(a, b)); }
  147. void crypto_wipe(void *secret, size_t size)
  148. {
  149. volatile u8 *v_secret = (u8*)secret;
  150. ZERO(v_secret, size);
  151. }
  152. /////////////////
  153. /// Chacha 20 ///
  154. /////////////////
  155. #define QUARTERROUND(a, b, c, d) \
  156. a += b; d = rotl32(d ^ a, 16); \
  157. c += d; b = rotl32(b ^ c, 12); \
  158. a += b; d = rotl32(d ^ a, 8); \
  159. c += d; b = rotl32(b ^ c, 7)
  160. static void chacha20_rounds(u32 out[16], const u32 in[16])
  161. {
  162. // The temporary variables make Chacha20 10% faster.
  163. u32 t0 = in[ 0]; u32 t1 = in[ 1]; u32 t2 = in[ 2]; u32 t3 = in[ 3];
  164. u32 t4 = in[ 4]; u32 t5 = in[ 5]; u32 t6 = in[ 6]; u32 t7 = in[ 7];
  165. u32 t8 = in[ 8]; u32 t9 = in[ 9]; u32 t10 = in[10]; u32 t11 = in[11];
  166. u32 t12 = in[12]; u32 t13 = in[13]; u32 t14 = in[14]; u32 t15 = in[15];
  167. FOR (i, 0, 10) { // 20 rounds, 2 rounds per loop.
  168. QUARTERROUND(t0, t4, t8 , t12); // column 0
  169. QUARTERROUND(t1, t5, t9 , t13); // column 1
  170. QUARTERROUND(t2, t6, t10, t14); // column 2
  171. QUARTERROUND(t3, t7, t11, t15); // column 3
  172. QUARTERROUND(t0, t5, t10, t15); // diagonal 0
  173. QUARTERROUND(t1, t6, t11, t12); // diagonal 1
  174. QUARTERROUND(t2, t7, t8 , t13); // diagonal 2
  175. QUARTERROUND(t3, t4, t9 , t14); // diagonal 3
  176. }
  177. out[ 0] = t0; out[ 1] = t1; out[ 2] = t2; out[ 3] = t3;
  178. out[ 4] = t4; out[ 5] = t5; out[ 6] = t6; out[ 7] = t7;
  179. out[ 8] = t8; out[ 9] = t9; out[10] = t10; out[11] = t11;
  180. out[12] = t12; out[13] = t13; out[14] = t14; out[15] = t15;
  181. }
  182. static const u8 *chacha20_constant = (const u8*)"expand 32-byte k"; // 16 bytes
  183. void crypto_chacha20_h(u8 out[32], const u8 key[32], const u8 in [16])
  184. {
  185. u32 block[16];
  186. load32_le_buf(block , chacha20_constant, 4);
  187. load32_le_buf(block + 4, key , 8);
  188. load32_le_buf(block + 12, in , 4);
  189. chacha20_rounds(block, block);
  190. // prevent reversal of the rounds by revealing only half of the buffer.
  191. store32_le_buf(out , block , 4); // constant
  192. store32_le_buf(out+16, block+12, 4); // counter and nonce
  193. WIPE_BUFFER(block);
  194. }
  195. u64 crypto_chacha20_djb(u8 *cipher_text, const u8 *plain_text,
  196. size_t text_size, const u8 key[32], const u8 nonce[8],
  197. u64 ctr)
  198. {
  199. u32 input[16];
  200. load32_le_buf(input , chacha20_constant, 4);
  201. load32_le_buf(input + 4, key , 8);
  202. load32_le_buf(input + 14, nonce , 2);
  203. input[12] = (u32) ctr;
  204. input[13] = (u32)(ctr >> 32);
  205. // Whole blocks
  206. u32 pool[16];
  207. size_t nb_blocks = text_size >> 6;
  208. FOR (i, 0, nb_blocks) {
  209. chacha20_rounds(pool, input);
  210. if (plain_text != 0) {
  211. FOR (j, 0, 16) {
  212. u32 p = pool[j] + input[j];
  213. store32_le(cipher_text, p ^ load32_le(plain_text));
  214. cipher_text += 4;
  215. plain_text += 4;
  216. }
  217. } else {
  218. FOR (j, 0, 16) {
  219. u32 p = pool[j] + input[j];
  220. store32_le(cipher_text, p);
  221. cipher_text += 4;
  222. }
  223. }
  224. input[12]++;
  225. if (input[12] == 0) {
  226. input[13]++;
  227. }
  228. }
  229. text_size &= 63;
  230. // Last (incomplete) block
  231. if (text_size > 0) {
  232. if (plain_text == 0) {
  233. plain_text = zero;
  234. }
  235. chacha20_rounds(pool, input);
  236. u8 tmp[64];
  237. FOR (i, 0, 16) {
  238. store32_le(tmp + i*4, pool[i] + input[i]);
  239. }
  240. FOR (i, 0, text_size) {
  241. cipher_text[i] = tmp[i] ^ plain_text[i];
  242. }
  243. WIPE_BUFFER(tmp);
  244. }
  245. ctr = input[12] + ((u64)input[13] << 32) + (text_size > 0);
  246. WIPE_BUFFER(pool);
  247. WIPE_BUFFER(input);
  248. return ctr;
  249. }
  250. u32 crypto_chacha20_ietf(u8 *cipher_text, const u8 *plain_text,
  251. size_t text_size,
  252. const u8 key[32], const u8 nonce[12], u32 ctr)
  253. {
  254. u64 big_ctr = ctr + ((u64)load32_le(nonce) << 32);
  255. return (u32)crypto_chacha20_djb(cipher_text, plain_text, text_size,
  256. key, nonce + 4, big_ctr);
  257. }
  258. u64 crypto_chacha20_x(u8 *cipher_text, const u8 *plain_text,
  259. size_t text_size,
  260. const u8 key[32], const u8 nonce[24], u64 ctr)
  261. {
  262. u8 sub_key[32];
  263. crypto_chacha20_h(sub_key, key, nonce);
  264. ctr = crypto_chacha20_djb(cipher_text, plain_text, text_size,
  265. sub_key, nonce + 16, ctr);
  266. WIPE_BUFFER(sub_key);
  267. return ctr;
  268. }
  269. /////////////////
  270. /// Poly 1305 ///
  271. /////////////////
  272. // h = (h + c) * r
  273. // preconditions:
  274. // ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff
  275. // ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff
  276. // end <= 1
  277. // Postcondition:
  278. // ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff
  279. static void poly_blocks(crypto_poly1305_ctx *ctx, const u8 *in,
  280. size_t nb_blocks, unsigned end)
  281. {
  282. // Local all the things!
  283. const u32 r0 = ctx->r[0];
  284. const u32 r1 = ctx->r[1];
  285. const u32 r2 = ctx->r[2];
  286. const u32 r3 = ctx->r[3];
  287. const u32 rr0 = (r0 >> 2) * 5; // lose 2 bits...
  288. const u32 rr1 = (r1 >> 2) + r1; // rr1 == (r1 >> 2) * 5
  289. const u32 rr2 = (r2 >> 2) + r2; // rr1 == (r2 >> 2) * 5
  290. const u32 rr3 = (r3 >> 2) + r3; // rr1 == (r3 >> 2) * 5
  291. const u32 rr4 = r0 & 3; // ...recover 2 bits
  292. u32 h0 = ctx->h[0];
  293. u32 h1 = ctx->h[1];
  294. u32 h2 = ctx->h[2];
  295. u32 h3 = ctx->h[3];
  296. u32 h4 = ctx->h[4];
  297. FOR (i, 0, nb_blocks) {
  298. // h + c, without carry propagation
  299. const u64 s0 = (u64)h0 + load32_le(in); in += 4;
  300. const u64 s1 = (u64)h1 + load32_le(in); in += 4;
  301. const u64 s2 = (u64)h2 + load32_le(in); in += 4;
  302. const u64 s3 = (u64)h3 + load32_le(in); in += 4;
  303. const u32 s4 = h4 + end;
  304. // (h + c) * r, without carry propagation
  305. const u64 x0 = s0*r0+ s1*rr3+ s2*rr2+ s3*rr1+ s4*rr0;
  306. const u64 x1 = s0*r1+ s1*r0 + s2*rr3+ s3*rr2+ s4*rr1;
  307. const u64 x2 = s0*r2+ s1*r1 + s2*r0 + s3*rr3+ s4*rr2;
  308. const u64 x3 = s0*r3+ s1*r2 + s2*r1 + s3*r0 + s4*rr3;
  309. const u32 x4 = s4*rr4;
  310. // partial reduction modulo 2^130 - 5
  311. const u32 u5 = x4 + (x3 >> 32); // u5 <= 7ffffff5
  312. const u64 u0 = (u5 >> 2) * 5 + (x0 & 0xffffffff);
  313. const u64 u1 = (u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32);
  314. const u64 u2 = (u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32);
  315. const u64 u3 = (u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32);
  316. const u32 u4 = (u3 >> 32) + (u5 & 3); // u4 <= 4
  317. // Update the hash
  318. h0 = u0 & 0xffffffff;
  319. h1 = u1 & 0xffffffff;
  320. h2 = u2 & 0xffffffff;
  321. h3 = u3 & 0xffffffff;
  322. h4 = u4;
  323. }
  324. ctx->h[0] = h0;
  325. ctx->h[1] = h1;
  326. ctx->h[2] = h2;
  327. ctx->h[3] = h3;
  328. ctx->h[4] = h4;
  329. }
  330. void crypto_poly1305_init(crypto_poly1305_ctx *ctx, const u8 key[32])
  331. {
  332. ZERO(ctx->h, 5); // Initial hash is zero
  333. ctx->c_idx = 0;
  334. // load r and pad (r has some of its bits cleared)
  335. load32_le_buf(ctx->r , key , 4);
  336. load32_le_buf(ctx->pad, key+16, 4);
  337. FOR (i, 0, 1) { ctx->r[i] &= 0x0fffffff; }
  338. FOR (i, 1, 4) { ctx->r[i] &= 0x0ffffffc; }
  339. }
  340. void crypto_poly1305_update(crypto_poly1305_ctx *ctx,
  341. const u8 *message, size_t message_size)
  342. {
  343. // Avoid undefined NULL pointer increments with empty messages
  344. if (message_size == 0) {
  345. return;
  346. }
  347. // Align ourselves with block boundaries
  348. size_t aligned = MIN(gap(ctx->c_idx, 16), message_size);
  349. FOR (i, 0, aligned) {
  350. ctx->c[ctx->c_idx] = *message;
  351. ctx->c_idx++;
  352. message++;
  353. message_size--;
  354. }
  355. // If block is complete, process it
  356. if (ctx->c_idx == 16) {
  357. poly_blocks(ctx, ctx->c, 1, 1);
  358. ctx->c_idx = 0;
  359. }
  360. // Process the message block by block
  361. size_t nb_blocks = message_size >> 4;
  362. poly_blocks(ctx, message, nb_blocks, 1);
  363. message += nb_blocks << 4;
  364. message_size &= 15;
  365. // remaining bytes (we never complete a block here)
  366. FOR (i, 0, message_size) {
  367. ctx->c[ctx->c_idx] = message[i];
  368. ctx->c_idx++;
  369. }
  370. }
  371. void crypto_poly1305_final(crypto_poly1305_ctx *ctx, u8 mac[16])
  372. {
  373. // Process the last block (if any)
  374. // We move the final 1 according to remaining input length
  375. // (this will add less than 2^130 to the last input block)
  376. if (ctx->c_idx != 0) {
  377. ZERO(ctx->c + ctx->c_idx, 16 - ctx->c_idx);
  378. ctx->c[ctx->c_idx] = 1;
  379. poly_blocks(ctx, ctx->c, 1, 0);
  380. }
  381. // check if we should subtract 2^130-5 by performing the
  382. // corresponding carry propagation.
  383. u64 c = 5;
  384. FOR (i, 0, 4) {
  385. c += ctx->h[i];
  386. c >>= 32;
  387. }
  388. c += ctx->h[4];
  389. c = (c >> 2) * 5; // shift the carry back to the beginning
  390. // c now indicates how many times we should subtract 2^130-5 (0 or 1)
  391. FOR (i, 0, 4) {
  392. c += (u64)ctx->h[i] + ctx->pad[i];
  393. store32_le(mac + i*4, (u32)c);
  394. c = c >> 32;
  395. }
  396. WIPE_CTX(ctx);
  397. }
  398. void crypto_poly1305(u8 mac[16], const u8 *message,
  399. size_t message_size, const u8 key[32])
  400. {
  401. crypto_poly1305_ctx ctx;
  402. crypto_poly1305_init (&ctx, key);
  403. crypto_poly1305_update(&ctx, message, message_size);
  404. crypto_poly1305_final (&ctx, mac);
  405. }
  406. ////////////////
  407. /// BLAKE2 b ///
  408. ////////////////
  409. static const u64 iv[8] = {
  410. 0x6a09e667f3bcc908, 0xbb67ae8584caa73b,
  411. 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
  412. 0x510e527fade682d1, 0x9b05688c2b3e6c1f,
  413. 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
  414. };
  415. static void blake2b_compress(crypto_blake2b_ctx *ctx, int is_last_block)
  416. {
  417. static const u8 sigma[12][16] = {
  418. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
  419. { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
  420. { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
  421. { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
  422. { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
  423. { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
  424. { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
  425. { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
  426. { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
  427. { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
  428. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
  429. { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
  430. };
  431. // increment input offset
  432. u64 *x = ctx->input_offset;
  433. size_t y = ctx->input_idx;
  434. x[0] += y;
  435. if (x[0] < y) {
  436. x[1]++;
  437. }
  438. // init work vector
  439. u64 v0 = ctx->hash[0]; u64 v8 = iv[0];
  440. u64 v1 = ctx->hash[1]; u64 v9 = iv[1];
  441. u64 v2 = ctx->hash[2]; u64 v10 = iv[2];
  442. u64 v3 = ctx->hash[3]; u64 v11 = iv[3];
  443. u64 v4 = ctx->hash[4]; u64 v12 = iv[4] ^ ctx->input_offset[0];
  444. u64 v5 = ctx->hash[5]; u64 v13 = iv[5] ^ ctx->input_offset[1];
  445. u64 v6 = ctx->hash[6]; u64 v14 = iv[6] ^ (u64)~(is_last_block - 1);
  446. u64 v7 = ctx->hash[7]; u64 v15 = iv[7];
  447. // mangle work vector
  448. u64 *input = ctx->input;
  449. #define BLAKE2_G(a, b, c, d, x, y) \
  450. a += b + x; d = rotr64(d ^ a, 32); \
  451. c += d; b = rotr64(b ^ c, 24); \
  452. a += b + y; d = rotr64(d ^ a, 16); \
  453. c += d; b = rotr64(b ^ c, 63)
  454. #define BLAKE2_ROUND(i) \
  455. BLAKE2_G(v0, v4, v8 , v12, input[sigma[i][ 0]], input[sigma[i][ 1]]); \
  456. BLAKE2_G(v1, v5, v9 , v13, input[sigma[i][ 2]], input[sigma[i][ 3]]); \
  457. BLAKE2_G(v2, v6, v10, v14, input[sigma[i][ 4]], input[sigma[i][ 5]]); \
  458. BLAKE2_G(v3, v7, v11, v15, input[sigma[i][ 6]], input[sigma[i][ 7]]); \
  459. BLAKE2_G(v0, v5, v10, v15, input[sigma[i][ 8]], input[sigma[i][ 9]]); \
  460. BLAKE2_G(v1, v6, v11, v12, input[sigma[i][10]], input[sigma[i][11]]); \
  461. BLAKE2_G(v2, v7, v8 , v13, input[sigma[i][12]], input[sigma[i][13]]); \
  462. BLAKE2_G(v3, v4, v9 , v14, input[sigma[i][14]], input[sigma[i][15]])
  463. #ifdef BLAKE2_NO_UNROLLING
  464. FOR (i, 0, 12) {
  465. BLAKE2_ROUND(i);
  466. }
  467. #else
  468. BLAKE2_ROUND(0); BLAKE2_ROUND(1); BLAKE2_ROUND(2); BLAKE2_ROUND(3);
  469. BLAKE2_ROUND(4); BLAKE2_ROUND(5); BLAKE2_ROUND(6); BLAKE2_ROUND(7);
  470. BLAKE2_ROUND(8); BLAKE2_ROUND(9); BLAKE2_ROUND(10); BLAKE2_ROUND(11);
  471. #endif
  472. // update hash
  473. ctx->hash[0] ^= v0 ^ v8; ctx->hash[1] ^= v1 ^ v9;
  474. ctx->hash[2] ^= v2 ^ v10; ctx->hash[3] ^= v3 ^ v11;
  475. ctx->hash[4] ^= v4 ^ v12; ctx->hash[5] ^= v5 ^ v13;
  476. ctx->hash[6] ^= v6 ^ v14; ctx->hash[7] ^= v7 ^ v15;
  477. }
  478. void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size,
  479. const u8 *key, size_t key_size)
  480. {
  481. // initial hash
  482. COPY(ctx->hash, iv, 8);
  483. ctx->hash[0] ^= 0x01010000 ^ (key_size << 8) ^ hash_size;
  484. ctx->input_offset[0] = 0; // beginning of the input, no offset
  485. ctx->input_offset[1] = 0; // beginning of the input, no offset
  486. ctx->hash_size = hash_size;
  487. ctx->input_idx = 0;
  488. ZERO(ctx->input, 16);
  489. // if there is a key, the first block is that key (padded with zeroes)
  490. if (key_size > 0) {
  491. u8 key_block[128] = {0};
  492. COPY(key_block, key, key_size);
  493. // same as calling crypto_blake2b_update(ctx, key_block , 128)
  494. load64_le_buf(ctx->input, key_block, 16);
  495. ctx->input_idx = 128;
  496. }
  497. }
  498. void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size)
  499. {
  500. crypto_blake2b_keyed_init(ctx, hash_size, 0, 0);
  501. }
  502. void crypto_blake2b_update(crypto_blake2b_ctx *ctx,
  503. const u8 *message, size_t message_size)
  504. {
  505. // Avoid undefined NULL pointer increments with empty messages
  506. if (message_size == 0) {
  507. return;
  508. }
  509. // Align with word boundaries
  510. if ((ctx->input_idx & 7) != 0) {
  511. size_t nb_bytes = MIN(gap(ctx->input_idx, 8), message_size);
  512. size_t word = ctx->input_idx >> 3;
  513. size_t byte = ctx->input_idx & 7;
  514. FOR (i, 0, nb_bytes) {
  515. ctx->input[word] |= (u64)message[i] << ((byte + i) << 3);
  516. }
  517. ctx->input_idx += nb_bytes;
  518. message += nb_bytes;
  519. message_size -= nb_bytes;
  520. }
  521. // Align with block boundaries (faster than byte by byte)
  522. if ((ctx->input_idx & 127) != 0) {
  523. size_t nb_words = MIN(gap(ctx->input_idx, 128), message_size) >> 3;
  524. load64_le_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words);
  525. ctx->input_idx += nb_words << 3;
  526. message += nb_words << 3;
  527. message_size -= nb_words << 3;
  528. }
  529. // Process block by block
  530. size_t nb_blocks = message_size >> 7;
  531. FOR (i, 0, nb_blocks) {
  532. if (ctx->input_idx == 128) {
  533. blake2b_compress(ctx, 0);
  534. }
  535. load64_le_buf(ctx->input, message, 16);
  536. message += 128;
  537. ctx->input_idx = 128;
  538. }
  539. message_size &= 127;
  540. if (message_size != 0) {
  541. // Compress block & flush input buffer as needed
  542. if (ctx->input_idx == 128) {
  543. blake2b_compress(ctx, 0);
  544. ctx->input_idx = 0;
  545. }
  546. if (ctx->input_idx == 0) {
  547. ZERO(ctx->input, 16);
  548. }
  549. // Fill remaining words (faster than byte by byte)
  550. size_t nb_words = message_size >> 3;
  551. load64_le_buf(ctx->input, message, nb_words);
  552. ctx->input_idx += nb_words << 3;
  553. message += nb_words << 3;
  554. message_size -= nb_words << 3;
  555. // Fill remaining bytes
  556. FOR (i, 0, message_size) {
  557. size_t word = ctx->input_idx >> 3;
  558. size_t byte = ctx->input_idx & 7;
  559. ctx->input[word] |= (u64)message[i] << (byte << 3);
  560. ctx->input_idx++;
  561. }
  562. }
  563. }
  564. void crypto_blake2b_final(crypto_blake2b_ctx *ctx, u8 *hash)
  565. {
  566. blake2b_compress(ctx, 1); // compress the last block
  567. size_t hash_size = MIN(ctx->hash_size, 64);
  568. size_t nb_words = hash_size >> 3;
  569. store64_le_buf(hash, ctx->hash, nb_words);
  570. FOR (i, nb_words << 3, hash_size) {
  571. hash[i] = (ctx->hash[i >> 3] >> (8 * (i & 7))) & 0xff;
  572. }
  573. WIPE_CTX(ctx);
  574. }
  575. void crypto_blake2b_keyed(u8 *hash, size_t hash_size,
  576. const u8 *key, size_t key_size,
  577. const u8 *message, size_t message_size)
  578. {
  579. crypto_blake2b_ctx ctx;
  580. crypto_blake2b_keyed_init(&ctx, hash_size, key, key_size);
  581. crypto_blake2b_update (&ctx, message, message_size);
  582. crypto_blake2b_final (&ctx, hash);
  583. }
  584. void crypto_blake2b(u8 *hash, size_t hash_size, const u8 *msg, size_t msg_size)
  585. {
  586. crypto_blake2b_keyed(hash, hash_size, 0, 0, msg, msg_size);
  587. }
  588. //////////////
  589. /// Argon2 ///
  590. //////////////
  591. // references to R, Z, Q etc. come from the spec
  592. // Argon2 operates on 1024 byte blocks.
  593. typedef struct { u64 a[128]; } blk;
  594. // updates a BLAKE2 hash with a 32 bit word, little endian.
  595. static void blake_update_32(crypto_blake2b_ctx *ctx, u32 input)
  596. {
  597. u8 buf[4];
  598. store32_le(buf, input);
  599. crypto_blake2b_update(ctx, buf, 4);
  600. WIPE_BUFFER(buf);
  601. }
  602. static void blake_update_32_buf(crypto_blake2b_ctx *ctx,
  603. const u8 *buf, u32 size)
  604. {
  605. blake_update_32(ctx, size);
  606. crypto_blake2b_update(ctx, buf, size);
  607. }
  608. static void copy_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] = in->a[i];}
  609. static void xor_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] ^= in->a[i];}
  610. // Hash with a virtually unlimited digest size.
  611. // Doesn't extract more entropy than the base hash function.
  612. // Mainly used for filling a whole kilobyte block with pseudo-random bytes.
  613. // (One could use a stream cipher with a seed hash as the key, but
  614. // this would introduce another dependency —and point of failure.)
  615. static void extended_hash(u8 *digest, u32 digest_size,
  616. const u8 *input , u32 input_size)
  617. {
  618. crypto_blake2b_ctx ctx;
  619. crypto_blake2b_init (&ctx, MIN(digest_size, 64));
  620. blake_update_32 (&ctx, digest_size);
  621. crypto_blake2b_update(&ctx, input, input_size);
  622. crypto_blake2b_final (&ctx, digest);
  623. if (digest_size > 64) {
  624. // the conversion to u64 avoids integer overflow on
  625. // ludicrously big hash sizes.
  626. u32 r = (u32)(((u64)digest_size + 31) >> 5) - 2;
  627. u32 i = 1;
  628. u32 in = 0;
  629. u32 out = 32;
  630. while (i < r) {
  631. // Input and output overlap. This is intentional
  632. crypto_blake2b(digest + out, 64, digest + in, 64);
  633. i += 1;
  634. in += 32;
  635. out += 32;
  636. }
  637. crypto_blake2b(digest + out, digest_size - (32 * r), digest + in , 64);
  638. }
  639. }
  640. #define LSB(x) ((u64)(u32)x)
  641. #define G(a, b, c, d) \
  642. a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 32); \
  643. c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 24); \
  644. a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 16); \
  645. c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 63)
  646. #define ROUND(v0, v1, v2, v3, v4, v5, v6, v7, \
  647. v8, v9, v10, v11, v12, v13, v14, v15) \
  648. G(v0, v4, v8, v12); G(v1, v5, v9, v13); \
  649. G(v2, v6, v10, v14); G(v3, v7, v11, v15); \
  650. G(v0, v5, v10, v15); G(v1, v6, v11, v12); \
  651. G(v2, v7, v8, v13); G(v3, v4, v9, v14)
  652. // Core of the compression function G. Computes Z from R in place.
  653. static void g_rounds(blk *b)
  654. {
  655. // column rounds (work_block = Q)
  656. for (int i = 0; i < 128; i += 16) {
  657. ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 2], b->a[i+ 3],
  658. b->a[i+ 4], b->a[i+ 5], b->a[i+ 6], b->a[i+ 7],
  659. b->a[i+ 8], b->a[i+ 9], b->a[i+10], b->a[i+11],
  660. b->a[i+12], b->a[i+13], b->a[i+14], b->a[i+15]);
  661. }
  662. // row rounds (b = Z)
  663. for (int i = 0; i < 16; i += 2) {
  664. ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 16], b->a[i+ 17],
  665. b->a[i+32], b->a[i+33], b->a[i+ 48], b->a[i+ 49],
  666. b->a[i+64], b->a[i+65], b->a[i+ 80], b->a[i+ 81],
  667. b->a[i+96], b->a[i+97], b->a[i+112], b->a[i+113]);
  668. }
  669. }
  670. const crypto_argon2_extras crypto_argon2_no_extras = { 0, 0, 0, 0 };
  671. void crypto_argon2(u8 *hash, u32 hash_size, void *work_area,
  672. crypto_argon2_config config,
  673. crypto_argon2_inputs inputs,
  674. crypto_argon2_extras extras)
  675. {
  676. const u32 segment_size = config.nb_blocks / config.nb_lanes / 4;
  677. const u32 lane_size = segment_size * 4;
  678. const u32 nb_blocks = lane_size * config.nb_lanes; // rounding down
  679. // work area seen as blocks (must be suitably aligned)
  680. blk *blocks = (blk*)work_area;
  681. {
  682. u8 initial_hash[72]; // 64 bytes plus 2 words for future hashes
  683. crypto_blake2b_ctx ctx;
  684. crypto_blake2b_init (&ctx, 64);
  685. blake_update_32 (&ctx, config.nb_lanes ); // p: number of "threads"
  686. blake_update_32 (&ctx, hash_size);
  687. blake_update_32 (&ctx, config.nb_blocks);
  688. blake_update_32 (&ctx, config.nb_passes);
  689. blake_update_32 (&ctx, 0x13); // v: version number
  690. blake_update_32 (&ctx, config.algorithm); // y: Argon2i, Argon2d...
  691. blake_update_32_buf (&ctx, inputs.pass, inputs.pass_size);
  692. blake_update_32_buf (&ctx, inputs.salt, inputs.salt_size);
  693. blake_update_32_buf (&ctx, extras.key, extras.key_size);
  694. blake_update_32_buf (&ctx, extras.ad, extras.ad_size);
  695. crypto_blake2b_final(&ctx, initial_hash); // fill 64 first bytes only
  696. // fill first 2 blocks of each lane
  697. u8 hash_area[1024];
  698. FOR_T(u32, l, 0, config.nb_lanes) {
  699. FOR_T(u32, i, 0, 2) {
  700. store32_le(initial_hash + 64, i); // first additional word
  701. store32_le(initial_hash + 68, l); // second additional word
  702. extended_hash(hash_area, 1024, initial_hash, 72);
  703. load64_le_buf(blocks[l * lane_size + i].a, hash_area, 128);
  704. }
  705. }
  706. WIPE_BUFFER(initial_hash);
  707. WIPE_BUFFER(hash_area);
  708. }
  709. // Argon2i and Argon2id start with constant time indexing
  710. int constant_time = config.algorithm != CRYPTO_ARGON2_D;
  711. // Fill (and re-fill) the rest of the blocks
  712. //
  713. // Note: even though each segment within the same slice can be
  714. // computed in parallel, (one thread per lane), we are computing
  715. // them sequentially, because Monocypher doesn't support threads.
  716. //
  717. // Yet optimal performance (and therefore security) requires one
  718. // thread per lane. The only reason Monocypher supports multiple
  719. // lanes is compatibility.
  720. blk tmp;
  721. FOR_T(u32, pass, 0, config.nb_passes) {
  722. FOR_T(u32, slice, 0, 4) {
  723. // On the first slice of the first pass,
  724. // blocks 0 and 1 are already filled, hence pass_offset.
  725. u32 pass_offset = pass == 0 && slice == 0 ? 2 : 0;
  726. u32 slice_offset = slice * segment_size;
  727. // Argon2id switches back to non-constant time indexing
  728. // after the first two slices of the first pass
  729. if (slice == 2 && config.algorithm == CRYPTO_ARGON2_ID) {
  730. constant_time = 0;
  731. }
  732. // Each iteration of the following loop may be performed in
  733. // a separate thread. All segments must be fully completed
  734. // before we start filling the next slice.
  735. FOR_T(u32, segment, 0, config.nb_lanes) {
  736. blk index_block;
  737. u32 index_ctr = 1;
  738. FOR_T (u32, block, pass_offset, segment_size) {
  739. // Current and previous blocks
  740. u32 lane_offset = segment * lane_size;
  741. blk *segment_start = blocks + lane_offset + slice_offset;
  742. blk *current = segment_start + block;
  743. blk *previous =
  744. block == 0 && slice_offset == 0
  745. ? segment_start + lane_size - 1
  746. : segment_start + block - 1;
  747. u64 index_seed;
  748. if (constant_time) {
  749. if (block == pass_offset || (block % 128) == 0) {
  750. // Fill or refresh deterministic indices block
  751. // seed the beginning of the block...
  752. ZERO(index_block.a, 128);
  753. index_block.a[0] = pass;
  754. index_block.a[1] = segment;
  755. index_block.a[2] = slice;
  756. index_block.a[3] = nb_blocks;
  757. index_block.a[4] = config.nb_passes;
  758. index_block.a[5] = config.algorithm;
  759. index_block.a[6] = index_ctr;
  760. index_ctr++;
  761. // ... then shuffle it
  762. copy_block(&tmp, &index_block);
  763. g_rounds (&index_block);
  764. xor_block (&index_block, &tmp);
  765. copy_block(&tmp, &index_block);
  766. g_rounds (&index_block);
  767. xor_block (&index_block, &tmp);
  768. }
  769. index_seed = index_block.a[block % 128];
  770. } else {
  771. index_seed = previous->a[0];
  772. }
  773. // Establish the reference set. *Approximately* comprises:
  774. // - The last 3 slices (if they exist yet)
  775. // - The already constructed blocks in the current segment
  776. u32 next_slice = ((slice + 1) % 4) * segment_size;
  777. u32 window_start = pass == 0 ? 0 : next_slice;
  778. u32 nb_segments = pass == 0 ? slice : 3;
  779. u64 lane =
  780. pass == 0 && slice == 0
  781. ? segment
  782. : (index_seed >> 32) % config.nb_lanes;
  783. u32 window_size =
  784. nb_segments * segment_size +
  785. (lane == segment ? block-1 :
  786. block == 0 ? (u32)-1 : 0);
  787. // Find reference block
  788. u64 j1 = index_seed & 0xffffffff; // block selector
  789. u64 x = (j1 * j1) >> 32;
  790. u64 y = (window_size * x) >> 32;
  791. u64 z = (window_size - 1) - y;
  792. u64 ref = (window_start + z) % lane_size;
  793. u32 index = lane * lane_size + (u32)ref;
  794. blk *reference = blocks + index;
  795. // Shuffle the previous & reference block
  796. // into the current block
  797. copy_block(&tmp, previous);
  798. xor_block (&tmp, reference);
  799. if (pass == 0) { copy_block(current, &tmp); }
  800. else { xor_block (current, &tmp); }
  801. g_rounds (&tmp);
  802. xor_block (current, &tmp);
  803. }
  804. }
  805. }
  806. }
  807. // Wipe temporary block
  808. volatile u64* p = tmp.a;
  809. ZERO(p, 128);
  810. // XOR last blocks of each lane
  811. blk *last_block = blocks + lane_size - 1;
  812. FOR_T (u32, lane, 1, config.nb_lanes) {
  813. blk *next_block = last_block + lane_size;
  814. xor_block(next_block, last_block);
  815. last_block = next_block;
  816. }
  817. // Serialize last block
  818. u8 final_block[1024];
  819. store64_le_buf(final_block, last_block->a, 128);
  820. // Wipe work area
  821. p = (u64*)work_area;
  822. ZERO(p, 128 * nb_blocks);
  823. // Hash the very last block with H' into the output hash
  824. extended_hash(hash, hash_size, final_block, 1024);
  825. WIPE_BUFFER(final_block);
  826. }
  827. ////////////////////////////////////
  828. /// Arithmetic modulo 2^255 - 19 ///
  829. ////////////////////////////////////
  830. // Originally taken from SUPERCOP's ref10 implementation.
  831. // A bit bigger than TweetNaCl, over 4 times faster.
  832. // field element
  833. typedef i32 fe[10];
  834. // field constants
  835. //
  836. // fe_one : 1
  837. // sqrtm1 : sqrt(-1)
  838. // d : -121665 / 121666
  839. // D2 : 2 * -121665 / 121666
  840. // lop_x, lop_y: low order point in Edwards coordinates
  841. // ufactor : -sqrt(-1) * 2
  842. // A2 : 486662^2 (A squared)
  843. static const fe fe_one = {1};
  844. static const fe sqrtm1 = {
  845. -32595792, -7943725, 9377950, 3500415, 12389472,
  846. -272473, -25146209, -2005654, 326686, 11406482,
  847. };
  848. static const fe d = {
  849. -10913610, 13857413, -15372611, 6949391, 114729,
  850. -8787816, -6275908, -3247719, -18696448, -12055116,
  851. };
  852. static const fe D2 = {
  853. -21827239, -5839606, -30745221, 13898782, 229458,
  854. 15978800, -12551817, -6495438, 29715968, 9444199,
  855. };
  856. static const fe lop_x = {
  857. 21352778, 5345713, 4660180, -8347857, 24143090,
  858. 14568123, 30185756, -12247770, -33528939, 8345319,
  859. };
  860. static const fe lop_y = {
  861. -6952922, -1265500, 6862341, -7057498, -4037696,
  862. -5447722, 31680899, -15325402, -19365852, 1569102,
  863. };
  864. static const fe ufactor = {
  865. -1917299, 15887451, -18755900, -7000830, -24778944,
  866. 544946, -16816446, 4011309, -653372, 10741468,
  867. };
  868. static const fe A2 = {
  869. 12721188, 3529, 0, 0, 0, 0, 0, 0, 0, 0,
  870. };
  871. static void fe_0(fe h) { ZERO(h , 10); }
  872. static void fe_1(fe h) { h[0] = 1; ZERO(h+1, 9); }
  873. static void fe_copy(fe h,const fe f ){FOR(i,0,10) h[i] = f[i]; }
  874. static void fe_neg (fe h,const fe f ){FOR(i,0,10) h[i] = -f[i]; }
  875. static void fe_add (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] + g[i];}
  876. static void fe_sub (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] - g[i];}
  877. static void fe_cswap(fe f, fe g, int b)
  878. {
  879. i32 mask = -b; // -1 = 0xffffffff
  880. FOR (i, 0, 10) {
  881. i32 x = (f[i] ^ g[i]) & mask;
  882. f[i] = f[i] ^ x;
  883. g[i] = g[i] ^ x;
  884. }
  885. }
  886. static void fe_ccopy(fe f, const fe g, int b)
  887. {
  888. i32 mask = -b; // -1 = 0xffffffff
  889. FOR (i, 0, 10) {
  890. i32 x = (f[i] ^ g[i]) & mask;
  891. f[i] = f[i] ^ x;
  892. }
  893. }
  894. // Signed carry propagation
  895. // ------------------------
  896. //
  897. // Let t be a number. It can be uniquely decomposed thus:
  898. //
  899. // t = h*2^26 + l
  900. // such that -2^25 <= l < 2^25
  901. //
  902. // Let c = (t + 2^25) / 2^26 (rounded down)
  903. // c = (h*2^26 + l + 2^25) / 2^26 (rounded down)
  904. // c = h + (l + 2^25) / 2^26 (rounded down)
  905. // c = h (exactly)
  906. // Because 0 <= l + 2^25 < 2^26
  907. //
  908. // Let u = t - c*2^26
  909. // u = h*2^26 + l - h*2^26
  910. // u = l
  911. // Therefore, -2^25 <= u < 2^25
  912. //
  913. // Additionally, if |t| < x, then |h| < x/2^26 (rounded down)
  914. //
  915. // Notations:
  916. // - In C, 1<<25 means 2^25.
  917. // - In C, x>>25 means floor(x / (2^25)).
  918. // - All of the above applies with 25 & 24 as well as 26 & 25.
  919. //
  920. //
  921. // Note on negative right shifts
  922. // -----------------------------
  923. //
  924. // In C, x >> n, where x is a negative integer, is implementation
  925. // defined. In practice, all platforms do arithmetic shift, which is
  926. // equivalent to division by 2^26, rounded down. Some compilers, like
  927. // GCC, even guarantee it.
  928. //
  929. // If we ever stumble upon a platform that does not propagate the sign
  930. // bit (we won't), visible failures will show at the slightest test, and
  931. // the signed shifts can be replaced by the following:
  932. //
  933. // typedef struct { i64 x:39; } s25;
  934. // typedef struct { i64 x:38; } s26;
  935. // i64 shift25(i64 x) { s25 s; s.x = ((u64)x)>>25; return s.x; }
  936. // i64 shift26(i64 x) { s26 s; s.x = ((u64)x)>>26; return s.x; }
  937. //
  938. // Current compilers cannot optimise this, causing a 30% drop in
  939. // performance. Fairly expensive for something that never happens.
  940. //
  941. //
  942. // Precondition
  943. // ------------
  944. //
  945. // |t0| < 2^63
  946. // |t1|..|t9| < 2^62
  947. //
  948. // Algorithm
  949. // ---------
  950. // c = t0 + 2^25 / 2^26 -- |c| <= 2^36
  951. // t0 -= c * 2^26 -- |t0| <= 2^25
  952. // t1 += c -- |t1| <= 2^63
  953. //
  954. // c = t4 + 2^25 / 2^26 -- |c| <= 2^36
  955. // t4 -= c * 2^26 -- |t4| <= 2^25
  956. // t5 += c -- |t5| <= 2^63
  957. //
  958. // c = t1 + 2^24 / 2^25 -- |c| <= 2^38
  959. // t1 -= c * 2^25 -- |t1| <= 2^24
  960. // t2 += c -- |t2| <= 2^63
  961. //
  962. // c = t5 + 2^24 / 2^25 -- |c| <= 2^38
  963. // t5 -= c * 2^25 -- |t5| <= 2^24
  964. // t6 += c -- |t6| <= 2^63
  965. //
  966. // c = t2 + 2^25 / 2^26 -- |c| <= 2^37
  967. // t2 -= c * 2^26 -- |t2| <= 2^25 < 1.1 * 2^25 (final t2)
  968. // t3 += c -- |t3| <= 2^63
  969. //
  970. // c = t6 + 2^25 / 2^26 -- |c| <= 2^37
  971. // t6 -= c * 2^26 -- |t6| <= 2^25 < 1.1 * 2^25 (final t6)
  972. // t7 += c -- |t7| <= 2^63
  973. //
  974. // c = t3 + 2^24 / 2^25 -- |c| <= 2^38
  975. // t3 -= c * 2^25 -- |t3| <= 2^24 < 1.1 * 2^24 (final t3)
  976. // t4 += c -- |t4| <= 2^25 + 2^38 < 2^39
  977. //
  978. // c = t7 + 2^24 / 2^25 -- |c| <= 2^38
  979. // t7 -= c * 2^25 -- |t7| <= 2^24 < 1.1 * 2^24 (final t7)
  980. // t8 += c -- |t8| <= 2^63
  981. //
  982. // c = t4 + 2^25 / 2^26 -- |c| <= 2^13
  983. // t4 -= c * 2^26 -- |t4| <= 2^25 < 1.1 * 2^25 (final t4)
  984. // t5 += c -- |t5| <= 2^24 + 2^13 < 1.1 * 2^24 (final t5)
  985. //
  986. // c = t8 + 2^25 / 2^26 -- |c| <= 2^37
  987. // t8 -= c * 2^26 -- |t8| <= 2^25 < 1.1 * 2^25 (final t8)
  988. // t9 += c -- |t9| <= 2^63
  989. //
  990. // c = t9 + 2^24 / 2^25 -- |c| <= 2^38
  991. // t9 -= c * 2^25 -- |t9| <= 2^24 < 1.1 * 2^24 (final t9)
  992. // t0 += c * 19 -- |t0| <= 2^25 + 2^38*19 < 2^44
  993. //
  994. // c = t0 + 2^25 / 2^26 -- |c| <= 2^18
  995. // t0 -= c * 2^26 -- |t0| <= 2^25 < 1.1 * 2^25 (final t0)
  996. // t1 += c -- |t1| <= 2^24 + 2^18 < 1.1 * 2^24 (final t1)
  997. //
  998. // Postcondition
  999. // -------------
  1000. // |t0|, |t2|, |t4|, |t6|, |t8| < 1.1 * 2^25
  1001. // |t1|, |t3|, |t5|, |t7|, |t9| < 1.1 * 2^24
  1002. #define FE_CARRY \
  1003. i64 c; \
  1004. c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \
  1005. c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \
  1006. c = (t1 + ((i64)1<<24)) >> 25; t1 -= c * ((i64)1 << 25); t2 += c; \
  1007. c = (t5 + ((i64)1<<24)) >> 25; t5 -= c * ((i64)1 << 25); t6 += c; \
  1008. c = (t2 + ((i64)1<<25)) >> 26; t2 -= c * ((i64)1 << 26); t3 += c; \
  1009. c = (t6 + ((i64)1<<25)) >> 26; t6 -= c * ((i64)1 << 26); t7 += c; \
  1010. c = (t3 + ((i64)1<<24)) >> 25; t3 -= c * ((i64)1 << 25); t4 += c; \
  1011. c = (t7 + ((i64)1<<24)) >> 25; t7 -= c * ((i64)1 << 25); t8 += c; \
  1012. c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \
  1013. c = (t8 + ((i64)1<<25)) >> 26; t8 -= c * ((i64)1 << 26); t9 += c; \
  1014. c = (t9 + ((i64)1<<24)) >> 25; t9 -= c * ((i64)1 << 25); t0 += c * 19; \
  1015. c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \
  1016. h[0]=(i32)t0; h[1]=(i32)t1; h[2]=(i32)t2; h[3]=(i32)t3; h[4]=(i32)t4; \
  1017. h[5]=(i32)t5; h[6]=(i32)t6; h[7]=(i32)t7; h[8]=(i32)t8; h[9]=(i32)t9
  1018. // Decodes a field element from a byte buffer.
  1019. // mask specifies how many bits we ignore.
  1020. // Traditionally we ignore 1. It's useful for EdDSA,
  1021. // which uses that bit to denote the sign of x.
  1022. // Elligator however uses positive representatives,
  1023. // which means ignoring 2 bits instead.
  1024. static void fe_frombytes_mask(fe h, const u8 s[32], unsigned nb_mask)
  1025. {
  1026. u32 mask = 0xffffff >> nb_mask;
  1027. i64 t0 = load32_le(s); // t0 < 2^32
  1028. i64 t1 = load24_le(s + 4) << 6; // t1 < 2^30
  1029. i64 t2 = load24_le(s + 7) << 5; // t2 < 2^29
  1030. i64 t3 = load24_le(s + 10) << 3; // t3 < 2^27
  1031. i64 t4 = load24_le(s + 13) << 2; // t4 < 2^26
  1032. i64 t5 = load32_le(s + 16); // t5 < 2^32
  1033. i64 t6 = load24_le(s + 20) << 7; // t6 < 2^31
  1034. i64 t7 = load24_le(s + 23) << 5; // t7 < 2^29
  1035. i64 t8 = load24_le(s + 26) << 4; // t8 < 2^28
  1036. i64 t9 = (load24_le(s + 29) & mask) << 2; // t9 < 2^25
  1037. FE_CARRY; // Carry precondition OK
  1038. }
  1039. static void fe_frombytes(fe h, const u8 s[32])
  1040. {
  1041. fe_frombytes_mask(h, s, 1);
  1042. }
  1043. // Precondition
  1044. // |h[0]|, |h[2]|, |h[4]|, |h[6]|, |h[8]| < 1.1 * 2^25
  1045. // |h[1]|, |h[3]|, |h[5]|, |h[7]|, |h[9]| < 1.1 * 2^24
  1046. //
  1047. // Therefore, |h| < 2^255-19
  1048. // There are two possibilities:
  1049. //
  1050. // - If h is positive, all we need to do is reduce its individual
  1051. // limbs down to their tight positive range.
  1052. // - If h is negative, we also need to add 2^255-19 to it.
  1053. // Or just remove 19 and chop off any excess bit.
  1054. static void fe_tobytes(u8 s[32], const fe h)
  1055. {
  1056. i32 t[10];
  1057. COPY(t, h, 10);
  1058. i32 q = (19 * t[9] + (((i32) 1) << 24)) >> 25;
  1059. // |t9| < 1.1 * 2^24
  1060. // -1.1 * 2^24 < t9 < 1.1 * 2^24
  1061. // -21 * 2^24 < 19 * t9 < 21 * 2^24
  1062. // -2^29 < 19 * t9 + 2^24 < 2^29
  1063. // -2^29 / 2^25 < (19 * t9 + 2^24) / 2^25 < 2^29 / 2^25
  1064. // -16 < (19 * t9 + 2^24) / 2^25 < 16
  1065. FOR (i, 0, 5) {
  1066. q += t[2*i ]; q >>= 26; // q = 0 or -1
  1067. q += t[2*i+1]; q >>= 25; // q = 0 or -1
  1068. }
  1069. // q = 0 iff h >= 0
  1070. // q = -1 iff h < 0
  1071. // Adding q * 19 to h reduces h to its proper range.
  1072. q *= 19; // Shift carry back to the beginning
  1073. FOR (i, 0, 5) {
  1074. t[i*2 ] += q; q = t[i*2 ] >> 26; t[i*2 ] -= q * ((i32)1 << 26);
  1075. t[i*2+1] += q; q = t[i*2+1] >> 25; t[i*2+1] -= q * ((i32)1 << 25);
  1076. }
  1077. // h is now fully reduced, and q represents the excess bit.
  1078. store32_le(s + 0, ((u32)t[0] >> 0) | ((u32)t[1] << 26));
  1079. store32_le(s + 4, ((u32)t[1] >> 6) | ((u32)t[2] << 19));
  1080. store32_le(s + 8, ((u32)t[2] >> 13) | ((u32)t[3] << 13));
  1081. store32_le(s + 12, ((u32)t[3] >> 19) | ((u32)t[4] << 6));
  1082. store32_le(s + 16, ((u32)t[5] >> 0) | ((u32)t[6] << 25));
  1083. store32_le(s + 20, ((u32)t[6] >> 7) | ((u32)t[7] << 19));
  1084. store32_le(s + 24, ((u32)t[7] >> 13) | ((u32)t[8] << 12));
  1085. store32_le(s + 28, ((u32)t[8] >> 20) | ((u32)t[9] << 6));
  1086. WIPE_BUFFER(t);
  1087. }
  1088. // Precondition
  1089. // -------------
  1090. // |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26
  1091. // |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25
  1092. //
  1093. // |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26
  1094. // |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25
  1095. static void fe_mul_small(fe h, const fe f, i32 g)
  1096. {
  1097. i64 t0 = f[0] * (i64) g; i64 t1 = f[1] * (i64) g;
  1098. i64 t2 = f[2] * (i64) g; i64 t3 = f[3] * (i64) g;
  1099. i64 t4 = f[4] * (i64) g; i64 t5 = f[5] * (i64) g;
  1100. i64 t6 = f[6] * (i64) g; i64 t7 = f[7] * (i64) g;
  1101. i64 t8 = f[8] * (i64) g; i64 t9 = f[9] * (i64) g;
  1102. // |t0|, |t2|, |t4|, |t6|, |t8| < 1.65 * 2^26 * 2^31 < 2^58
  1103. // |t1|, |t3|, |t5|, |t7|, |t9| < 1.65 * 2^25 * 2^31 < 2^57
  1104. FE_CARRY; // Carry precondition OK
  1105. }
  1106. // Precondition
  1107. // -------------
  1108. // |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26
  1109. // |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25
  1110. //
  1111. // |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26
  1112. // |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25
  1113. static void fe_mul(fe h, const fe f, const fe g)
  1114. {
  1115. // Everything is unrolled and put in temporary variables.
  1116. // We could roll the loop, but that would make curve25519 twice as slow.
  1117. i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4];
  1118. i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9];
  1119. i32 g0 = g[0]; i32 g1 = g[1]; i32 g2 = g[2]; i32 g3 = g[3]; i32 g4 = g[4];
  1120. i32 g5 = g[5]; i32 g6 = g[6]; i32 g7 = g[7]; i32 g8 = g[8]; i32 g9 = g[9];
  1121. i32 F1 = f1*2; i32 F3 = f3*2; i32 F5 = f5*2; i32 F7 = f7*2; i32 F9 = f9*2;
  1122. i32 G1 = g1*19; i32 G2 = g2*19; i32 G3 = g3*19;
  1123. i32 G4 = g4*19; i32 G5 = g5*19; i32 G6 = g6*19;
  1124. i32 G7 = g7*19; i32 G8 = g8*19; i32 G9 = g9*19;
  1125. // |F1|, |F3|, |F5|, |F7|, |F9| < 1.65 * 2^26
  1126. // |G0|, |G2|, |G4|, |G6|, |G8| < 2^31
  1127. // |G1|, |G3|, |G5|, |G7|, |G9| < 2^30
  1128. i64 t0 = f0*(i64)g0 + F1*(i64)G9 + f2*(i64)G8 + F3*(i64)G7 + f4*(i64)G6
  1129. + F5*(i64)G5 + f6*(i64)G4 + F7*(i64)G3 + f8*(i64)G2 + F9*(i64)G1;
  1130. i64 t1 = f0*(i64)g1 + f1*(i64)g0 + f2*(i64)G9 + f3*(i64)G8 + f4*(i64)G7
  1131. + f5*(i64)G6 + f6*(i64)G5 + f7*(i64)G4 + f8*(i64)G3 + f9*(i64)G2;
  1132. i64 t2 = f0*(i64)g2 + F1*(i64)g1 + f2*(i64)g0 + F3*(i64)G9 + f4*(i64)G8
  1133. + F5*(i64)G7 + f6*(i64)G6 + F7*(i64)G5 + f8*(i64)G4 + F9*(i64)G3;
  1134. i64 t3 = f0*(i64)g3 + f1*(i64)g2 + f2*(i64)g1 + f3*(i64)g0 + f4*(i64)G9
  1135. + f5*(i64)G8 + f6*(i64)G7 + f7*(i64)G6 + f8*(i64)G5 + f9*(i64)G4;
  1136. i64 t4 = f0*(i64)g4 + F1*(i64)g3 + f2*(i64)g2 + F3*(i64)g1 + f4*(i64)g0
  1137. + F5*(i64)G9 + f6*(i64)G8 + F7*(i64)G7 + f8*(i64)G6 + F9*(i64)G5;
  1138. i64 t5 = f0*(i64)g5 + f1*(i64)g4 + f2*(i64)g3 + f3*(i64)g2 + f4*(i64)g1
  1139. + f5*(i64)g0 + f6*(i64)G9 + f7*(i64)G8 + f8*(i64)G7 + f9*(i64)G6;
  1140. i64 t6 = f0*(i64)g6 + F1*(i64)g5 + f2*(i64)g4 + F3*(i64)g3 + f4*(i64)g2
  1141. + F5*(i64)g1 + f6*(i64)g0 + F7*(i64)G9 + f8*(i64)G8 + F9*(i64)G7;
  1142. i64 t7 = f0*(i64)g7 + f1*(i64)g6 + f2*(i64)g5 + f3*(i64)g4 + f4*(i64)g3
  1143. + f5*(i64)g2 + f6*(i64)g1 + f7*(i64)g0 + f8*(i64)G9 + f9*(i64)G8;
  1144. i64 t8 = f0*(i64)g8 + F1*(i64)g7 + f2*(i64)g6 + F3*(i64)g5 + f4*(i64)g4
  1145. + F5*(i64)g3 + f6*(i64)g2 + F7*(i64)g1 + f8*(i64)g0 + F9*(i64)G9;
  1146. i64 t9 = f0*(i64)g9 + f1*(i64)g8 + f2*(i64)g7 + f3*(i64)g6 + f4*(i64)g5
  1147. + f5*(i64)g4 + f6*(i64)g3 + f7*(i64)g2 + f8*(i64)g1 + f9*(i64)g0;
  1148. // t0 < 0.67 * 2^61
  1149. // t1 < 0.41 * 2^61
  1150. // t2 < 0.52 * 2^61
  1151. // t3 < 0.32 * 2^61
  1152. // t4 < 0.38 * 2^61
  1153. // t5 < 0.22 * 2^61
  1154. // t6 < 0.23 * 2^61
  1155. // t7 < 0.13 * 2^61
  1156. // t8 < 0.09 * 2^61
  1157. // t9 < 0.03 * 2^61
  1158. FE_CARRY; // Everything below 2^62, Carry precondition OK
  1159. }
  1160. // Precondition
  1161. // -------------
  1162. // |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26
  1163. // |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25
  1164. //
  1165. // Note: we could use fe_mul() for this, but this is significantly faster
  1166. static void fe_sq(fe h, const fe f)
  1167. {
  1168. i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4];
  1169. i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9];
  1170. i32 f0_2 = f0*2; i32 f1_2 = f1*2; i32 f2_2 = f2*2; i32 f3_2 = f3*2;
  1171. i32 f4_2 = f4*2; i32 f5_2 = f5*2; i32 f6_2 = f6*2; i32 f7_2 = f7*2;
  1172. i32 f5_38 = f5*38; i32 f6_19 = f6*19; i32 f7_38 = f7*38;
  1173. i32 f8_19 = f8*19; i32 f9_38 = f9*38;
  1174. // |f0_2| , |f2_2| , |f4_2| , |f6_2| , |f8_2| < 1.65 * 2^27
  1175. // |f1_2| , |f3_2| , |f5_2| , |f7_2| , |f9_2| < 1.65 * 2^26
  1176. // |f5_38|, |f6_19|, |f7_38|, |f8_19|, |f9_38| < 2^31
  1177. i64 t0 = f0 *(i64)f0 + f1_2*(i64)f9_38 + f2_2*(i64)f8_19
  1178. + f3_2*(i64)f7_38 + f4_2*(i64)f6_19 + f5 *(i64)f5_38;
  1179. i64 t1 = f0_2*(i64)f1 + f2 *(i64)f9_38 + f3_2*(i64)f8_19
  1180. + f4 *(i64)f7_38 + f5_2*(i64)f6_19;
  1181. i64 t2 = f0_2*(i64)f2 + f1_2*(i64)f1 + f3_2*(i64)f9_38
  1182. + f4_2*(i64)f8_19 + f5_2*(i64)f7_38 + f6 *(i64)f6_19;
  1183. i64 t3 = f0_2*(i64)f3 + f1_2*(i64)f2 + f4 *(i64)f9_38
  1184. + f5_2*(i64)f8_19 + f6 *(i64)f7_38;
  1185. i64 t4 = f0_2*(i64)f4 + f1_2*(i64)f3_2 + f2 *(i64)f2
  1186. + f5_2*(i64)f9_38 + f6_2*(i64)f8_19 + f7 *(i64)f7_38;
  1187. i64 t5 = f0_2*(i64)f5 + f1_2*(i64)f4 + f2_2*(i64)f3
  1188. + f6 *(i64)f9_38 + f7_2*(i64)f8_19;
  1189. i64 t6 = f0_2*(i64)f6 + f1_2*(i64)f5_2 + f2_2*(i64)f4
  1190. + f3_2*(i64)f3 + f7_2*(i64)f9_38 + f8 *(i64)f8_19;
  1191. i64 t7 = f0_2*(i64)f7 + f1_2*(i64)f6 + f2_2*(i64)f5
  1192. + f3_2*(i64)f4 + f8 *(i64)f9_38;
  1193. i64 t8 = f0_2*(i64)f8 + f1_2*(i64)f7_2 + f2_2*(i64)f6
  1194. + f3_2*(i64)f5_2 + f4 *(i64)f4 + f9 *(i64)f9_38;
  1195. i64 t9 = f0_2*(i64)f9 + f1_2*(i64)f8 + f2_2*(i64)f7
  1196. + f3_2*(i64)f6 + f4 *(i64)f5_2;
  1197. // t0 < 0.67 * 2^61
  1198. // t1 < 0.41 * 2^61
  1199. // t2 < 0.52 * 2^61
  1200. // t3 < 0.32 * 2^61
  1201. // t4 < 0.38 * 2^61
  1202. // t5 < 0.22 * 2^61
  1203. // t6 < 0.23 * 2^61
  1204. // t7 < 0.13 * 2^61
  1205. // t8 < 0.09 * 2^61
  1206. // t9 < 0.03 * 2^61
  1207. FE_CARRY;
  1208. }
  1209. // Parity check. Returns 0 if even, 1 if odd
  1210. static int fe_isodd(const fe f)
  1211. {
  1212. u8 s[32];
  1213. fe_tobytes(s, f);
  1214. u8 isodd = s[0] & 1;
  1215. WIPE_BUFFER(s);
  1216. return isodd;
  1217. }
  1218. // Returns 1 if equal, 0 if not equal
  1219. static int fe_isequal(const fe f, const fe g)
  1220. {
  1221. u8 fs[32];
  1222. u8 gs[32];
  1223. fe_tobytes(fs, f);
  1224. fe_tobytes(gs, g);
  1225. int isdifferent = crypto_verify32(fs, gs);
  1226. WIPE_BUFFER(fs);
  1227. WIPE_BUFFER(gs);
  1228. return 1 + isdifferent;
  1229. }
  1230. // Inverse square root.
  1231. // Returns true if x is a square, false otherwise.
  1232. // After the call:
  1233. // isr = sqrt(1/x) if x is a non-zero square.
  1234. // isr = sqrt(sqrt(-1)/x) if x is not a square.
  1235. // isr = 0 if x is zero.
  1236. // We do not guarantee the sign of the square root.
  1237. //
  1238. // Notes:
  1239. // Let quartic = x^((p-1)/4)
  1240. //
  1241. // x^((p-1)/2) = chi(x)
  1242. // quartic^2 = chi(x)
  1243. // quartic = sqrt(chi(x))
  1244. // quartic = 1 or -1 or sqrt(-1) or -sqrt(-1)
  1245. //
  1246. // Note that x is a square if quartic is 1 or -1
  1247. // There are 4 cases to consider:
  1248. //
  1249. // if quartic = 1 (x is a square)
  1250. // then x^((p-1)/4) = 1
  1251. // x^((p-5)/4) * x = 1
  1252. // x^((p-5)/4) = 1/x
  1253. // x^((p-5)/8) = sqrt(1/x) or -sqrt(1/x)
  1254. //
  1255. // if quartic = -1 (x is a square)
  1256. // then x^((p-1)/4) = -1
  1257. // x^((p-5)/4) * x = -1
  1258. // x^((p-5)/4) = -1/x
  1259. // x^((p-5)/8) = sqrt(-1) / sqrt(x)
  1260. // x^((p-5)/8) * sqrt(-1) = sqrt(-1)^2 / sqrt(x)
  1261. // x^((p-5)/8) * sqrt(-1) = -1/sqrt(x)
  1262. // x^((p-5)/8) * sqrt(-1) = -sqrt(1/x) or sqrt(1/x)
  1263. //
  1264. // if quartic = sqrt(-1) (x is not a square)
  1265. // then x^((p-1)/4) = sqrt(-1)
  1266. // x^((p-5)/4) * x = sqrt(-1)
  1267. // x^((p-5)/4) = sqrt(-1)/x
  1268. // x^((p-5)/8) = sqrt(sqrt(-1)/x) or -sqrt(sqrt(-1)/x)
  1269. //
  1270. // Note that the product of two non-squares is always a square:
  1271. // For any non-squares a and b, chi(a) = -1 and chi(b) = -1.
  1272. // Since chi(x) = x^((p-1)/2), chi(a)*chi(b) = chi(a*b) = 1.
  1273. // Therefore a*b is a square.
  1274. //
  1275. // Since sqrt(-1) and x are both non-squares, their product is a
  1276. // square, and we can compute their square root.
  1277. //
  1278. // if quartic = -sqrt(-1) (x is not a square)
  1279. // then x^((p-1)/4) = -sqrt(-1)
  1280. // x^((p-5)/4) * x = -sqrt(-1)
  1281. // x^((p-5)/4) = -sqrt(-1)/x
  1282. // x^((p-5)/8) = sqrt(-sqrt(-1)/x)
  1283. // x^((p-5)/8) = sqrt( sqrt(-1)/x) * sqrt(-1)
  1284. // x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * sqrt(-1)^2
  1285. // x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * -1
  1286. // x^((p-5)/8) * sqrt(-1) = -sqrt(sqrt(-1)/x) or sqrt(sqrt(-1)/x)
  1287. static int invsqrt(fe isr, const fe x)
  1288. {
  1289. fe t0, t1, t2;
  1290. // t0 = x^((p-5)/8)
  1291. // Can be achieved with a simple double & add ladder,
  1292. // but it would be slower.
  1293. fe_sq(t0, x);
  1294. fe_sq(t1,t0); fe_sq(t1, t1); fe_mul(t1, x, t1);
  1295. fe_mul(t0, t0, t1);
  1296. fe_sq(t0, t0); fe_mul(t0, t1, t0);
  1297. fe_sq(t1, t0); FOR (i, 1, 5) { fe_sq(t1, t1); } fe_mul(t0, t1, t0);
  1298. fe_sq(t1, t0); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t1, t1, t0);
  1299. fe_sq(t2, t1); FOR (i, 1, 20) { fe_sq(t2, t2); } fe_mul(t1, t2, t1);
  1300. fe_sq(t1, t1); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t0, t1, t0);
  1301. fe_sq(t1, t0); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t1, t1, t0);
  1302. fe_sq(t2, t1); FOR (i, 1, 100) { fe_sq(t2, t2); } fe_mul(t1, t2, t1);
  1303. fe_sq(t1, t1); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t0, t1, t0);
  1304. fe_sq(t0, t0); FOR (i, 1, 2) { fe_sq(t0, t0); } fe_mul(t0, t0, x);
  1305. // quartic = x^((p-1)/4)
  1306. i32 *quartic = t1;
  1307. fe_sq (quartic, t0);
  1308. fe_mul(quartic, quartic, x);
  1309. i32 *check = t2;
  1310. fe_0 (check); int z0 = fe_isequal(x , check);
  1311. fe_1 (check); int p1 = fe_isequal(quartic, check);
  1312. fe_neg(check, check ); int m1 = fe_isequal(quartic, check);
  1313. fe_neg(check, sqrtm1); int ms = fe_isequal(quartic, check);
  1314. // if quartic == -1 or sqrt(-1)
  1315. // then isr = x^((p-1)/4) * sqrt(-1)
  1316. // else isr = x^((p-1)/4)
  1317. fe_mul(isr, t0, sqrtm1);
  1318. fe_ccopy(isr, t0, 1 - (m1 | ms));
  1319. WIPE_BUFFER(t0);
  1320. WIPE_BUFFER(t1);
  1321. WIPE_BUFFER(t2);
  1322. return p1 | m1 | z0;
  1323. }
  1324. // Inverse in terms of inverse square root.
  1325. // Requires two additional squarings to get rid of the sign.
  1326. //
  1327. // 1/x = x * (+invsqrt(x^2))^2
  1328. // = x * (-invsqrt(x^2))^2
  1329. //
  1330. // A fully optimised exponentiation by p-1 would save 6 field
  1331. // multiplications, but it would require more code.
  1332. static void fe_invert(fe out, const fe x)
  1333. {
  1334. fe tmp;
  1335. fe_sq(tmp, x);
  1336. invsqrt(tmp, tmp);
  1337. fe_sq(tmp, tmp);
  1338. fe_mul(out, tmp, x);
  1339. WIPE_BUFFER(tmp);
  1340. }
  1341. // trim a scalar for scalar multiplication
  1342. void crypto_eddsa_trim_scalar(u8 out[32], const u8 in[32])
  1343. {
  1344. COPY(out, in, 32);
  1345. out[ 0] &= 248;
  1346. out[31] &= 127;
  1347. out[31] |= 64;
  1348. }
  1349. // get bit from scalar at position i
  1350. static int scalar_bit(const u8 s[32], int i)
  1351. {
  1352. if (i < 0) { return 0; } // handle -1 for sliding windows
  1353. return (s[i>>3] >> (i&7)) & 1;
  1354. }
  1355. ///////////////
  1356. /// X-25519 /// Taken from SUPERCOP's ref10 implementation.
  1357. ///////////////
  1358. static void scalarmult(u8 q[32], const u8 scalar[32], const u8 p[32],
  1359. int nb_bits)
  1360. {
  1361. // computes the scalar product
  1362. fe x1;
  1363. fe_frombytes(x1, p);
  1364. // computes the actual scalar product (the result is in x2 and z2)
  1365. fe x2, z2, x3, z3, t0, t1;
  1366. // Montgomery ladder
  1367. // In projective coordinates, to avoid divisions: x = X / Z
  1368. // We don't care about the y coordinate, it's only 1 bit of information
  1369. fe_1(x2); fe_0(z2); // "zero" point
  1370. fe_copy(x3, x1); fe_1(z3); // "one" point
  1371. int swap = 0;
  1372. for (int pos = nb_bits-1; pos >= 0; --pos) {
  1373. // constant time conditional swap before ladder step
  1374. int b = scalar_bit(scalar, pos);
  1375. swap ^= b; // xor trick avoids swapping at the end of the loop
  1376. fe_cswap(x2, x3, swap);
  1377. fe_cswap(z2, z3, swap);
  1378. swap = b; // anticipates one last swap after the loop
  1379. // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3)
  1380. // with differential addition
  1381. fe_sub(t0, x3, z3);
  1382. fe_sub(t1, x2, z2);
  1383. fe_add(x2, x2, z2);
  1384. fe_add(z2, x3, z3);
  1385. fe_mul(z3, t0, x2);
  1386. fe_mul(z2, z2, t1);
  1387. fe_sq (t0, t1 );
  1388. fe_sq (t1, x2 );
  1389. fe_add(x3, z3, z2);
  1390. fe_sub(z2, z3, z2);
  1391. fe_mul(x2, t1, t0);
  1392. fe_sub(t1, t1, t0);
  1393. fe_sq (z2, z2 );
  1394. fe_mul_small(z3, t1, 121666);
  1395. fe_sq (x3, x3 );
  1396. fe_add(t0, t0, z3);
  1397. fe_mul(z3, x1, z2);
  1398. fe_mul(z2, t1, t0);
  1399. }
  1400. // last swap is necessary to compensate for the xor trick
  1401. // Note: after this swap, P3 == P2 + P1.
  1402. fe_cswap(x2, x3, swap);
  1403. fe_cswap(z2, z3, swap);
  1404. // normalises the coordinates: x == X / Z
  1405. fe_invert(z2, z2);
  1406. fe_mul(x2, x2, z2);
  1407. fe_tobytes(q, x2);
  1408. WIPE_BUFFER(x1);
  1409. WIPE_BUFFER(x2); WIPE_BUFFER(z2); WIPE_BUFFER(t0);
  1410. WIPE_BUFFER(x3); WIPE_BUFFER(z3); WIPE_BUFFER(t1);
  1411. }
  1412. void crypto_x25519(u8 raw_shared_secret[32],
  1413. const u8 your_secret_key [32],
  1414. const u8 their_public_key [32])
  1415. {
  1416. // restrict the possible scalar values
  1417. u8 e[32];
  1418. crypto_eddsa_trim_scalar(e, your_secret_key);
  1419. scalarmult(raw_shared_secret, e, their_public_key, 255);
  1420. WIPE_BUFFER(e);
  1421. }
  1422. void crypto_x25519_public_key(u8 public_key[32],
  1423. const u8 secret_key[32])
  1424. {
  1425. static const u8 base_point[32] = {9};
  1426. crypto_x25519(public_key, secret_key, base_point);
  1427. }
  1428. ///////////////////////////
  1429. /// Arithmetic modulo L ///
  1430. ///////////////////////////
  1431. static const u32 L[8] = {
  1432. 0x5cf5d3ed, 0x5812631a, 0xa2f79cd6, 0x14def9de,
  1433. 0x00000000, 0x00000000, 0x00000000, 0x10000000,
  1434. };
  1435. // p = a*b + p
  1436. static void multiply(u32 p[16], const u32 a[8], const u32 b[8])
  1437. {
  1438. FOR (i, 0, 8) {
  1439. u64 carry = 0;
  1440. FOR (j, 0, 8) {
  1441. carry += p[i+j] + (u64)a[i] * b[j];
  1442. p[i+j] = (u32)carry;
  1443. carry >>= 32;
  1444. }
  1445. p[i+8] = (u32)carry;
  1446. }
  1447. }
  1448. static int is_above_l(const u32 x[8])
  1449. {
  1450. // We work with L directly, in a 2's complement encoding
  1451. // (-L == ~L + 1)
  1452. u64 carry = 1;
  1453. FOR (i, 0, 8) {
  1454. carry += (u64)x[i] + (~L[i] & 0xffffffff);
  1455. carry >>= 32;
  1456. }
  1457. return (int)carry; // carry is either 0 or 1
  1458. }
  1459. // Final reduction modulo L, by conditionally removing L.
  1460. // if x < l , then r = x
  1461. // if l <= x 2*l, then r = x-l
  1462. // otherwise the result will be wrong
  1463. static void remove_l(u32 r[8], const u32 x[8])
  1464. {
  1465. u64 carry = (u64)is_above_l(x);
  1466. u32 mask = ~(u32)carry + 1; // carry == 0 or 1
  1467. FOR (i, 0, 8) {
  1468. carry += (u64)x[i] + (~L[i] & mask);
  1469. r[i] = (u32)carry;
  1470. carry >>= 32;
  1471. }
  1472. }
  1473. // Full reduction modulo L (Barrett reduction)
  1474. static void mod_l(u8 reduced[32], const u32 x[16])
  1475. {
  1476. static const u32 r[9] = {
  1477. 0x0a2c131b,0xed9ce5a3,0x086329a7,0x2106215d,
  1478. 0xffffffeb,0xffffffff,0xffffffff,0xffffffff,0xf,
  1479. };
  1480. // xr = x * r
  1481. u32 xr[25] = {0};
  1482. FOR (i, 0, 9) {
  1483. u64 carry = 0;
  1484. FOR (j, 0, 16) {
  1485. carry += xr[i+j] + (u64)r[i] * x[j];
  1486. xr[i+j] = (u32)carry;
  1487. carry >>= 32;
  1488. }
  1489. xr[i+16] = (u32)carry;
  1490. }
  1491. // xr = floor(xr / 2^512) * L
  1492. // Since the result is guaranteed to be below 2*L,
  1493. // it is enough to only compute the first 256 bits.
  1494. // The division is performed by saying xr[i+16]. (16 * 32 = 512)
  1495. ZERO(xr, 8);
  1496. FOR (i, 0, 8) {
  1497. u64 carry = 0;
  1498. FOR (j, 0, 8-i) {
  1499. carry += xr[i+j] + (u64)xr[i+16] * L[j];
  1500. xr[i+j] = (u32)carry;
  1501. carry >>= 32;
  1502. }
  1503. }
  1504. // xr = x - xr
  1505. u64 carry = 1;
  1506. FOR (i, 0, 8) {
  1507. carry += (u64)x[i] + (~xr[i] & 0xffffffff);
  1508. xr[i] = (u32)carry;
  1509. carry >>= 32;
  1510. }
  1511. // Final reduction modulo L (conditional subtraction)
  1512. remove_l(xr, xr);
  1513. store32_le_buf(reduced, xr, 8);
  1514. WIPE_BUFFER(xr);
  1515. }
  1516. void crypto_eddsa_reduce(u8 reduced[32], const u8 expanded[64])
  1517. {
  1518. u32 x[16];
  1519. load32_le_buf(x, expanded, 16);
  1520. mod_l(reduced, x);
  1521. WIPE_BUFFER(x);
  1522. }
  1523. // r = (a * b) + c
  1524. void crypto_eddsa_mul_add(u8 r[32],
  1525. const u8 a[32], const u8 b[32], const u8 c[32])
  1526. {
  1527. u32 A[8]; load32_le_buf(A, a, 8);
  1528. u32 B[8]; load32_le_buf(B, b, 8);
  1529. u32 p[16]; load32_le_buf(p, c, 8); ZERO(p + 8, 8);
  1530. multiply(p, A, B);
  1531. mod_l(r, p);
  1532. WIPE_BUFFER(p);
  1533. WIPE_BUFFER(A);
  1534. WIPE_BUFFER(B);
  1535. }
  1536. ///////////////
  1537. /// Ed25519 ///
  1538. ///////////////
  1539. // Point (group element, ge) in a twisted Edwards curve,
  1540. // in extended projective coordinates.
  1541. // ge : x = X/Z, y = Y/Z, T = XY/Z
  1542. // ge_cached : Yp = X+Y, Ym = X-Y, T2 = T*D2
  1543. // ge_precomp: Z = 1
  1544. typedef struct { fe X; fe Y; fe Z; fe T; } ge;
  1545. typedef struct { fe Yp; fe Ym; fe Z; fe T2; } ge_cached;
  1546. typedef struct { fe Yp; fe Ym; fe T2; } ge_precomp;
  1547. static void ge_zero(ge *p)
  1548. {
  1549. fe_0(p->X);
  1550. fe_1(p->Y);
  1551. fe_1(p->Z);
  1552. fe_0(p->T);
  1553. }
  1554. static void ge_tobytes(u8 s[32], const ge *h)
  1555. {
  1556. fe recip, x, y;
  1557. fe_invert(recip, h->Z);
  1558. fe_mul(x, h->X, recip);
  1559. fe_mul(y, h->Y, recip);
  1560. fe_tobytes(s, y);
  1561. s[31] ^= fe_isodd(x) << 7;
  1562. WIPE_BUFFER(recip);
  1563. WIPE_BUFFER(x);
  1564. WIPE_BUFFER(y);
  1565. }
  1566. // h = -s, where s is a point encoded in 32 bytes
  1567. //
  1568. // Variable time! Inputs must not be secret!
  1569. // => Use only to *check* signatures.
  1570. //
  1571. // From the specifications:
  1572. // The encoding of s contains y and the sign of x
  1573. // x = sqrt((y^2 - 1) / (d*y^2 + 1))
  1574. // In extended coordinates:
  1575. // X = x, Y = y, Z = 1, T = x*y
  1576. //
  1577. // Note that num * den is a square iff num / den is a square
  1578. // If num * den is not a square, the point was not on the curve.
  1579. // From the above:
  1580. // Let num = y^2 - 1
  1581. // Let den = d*y^2 + 1
  1582. // x = sqrt((y^2 - 1) / (d*y^2 + 1))
  1583. // x = sqrt(num / den)
  1584. // x = sqrt(num^2 / (num * den))
  1585. // x = num * sqrt(1 / (num * den))
  1586. //
  1587. // Therefore, we can just compute:
  1588. // num = y^2 - 1
  1589. // den = d*y^2 + 1
  1590. // isr = invsqrt(num * den) // abort if not square
  1591. // x = num * isr
  1592. // Finally, negate x if its sign is not as specified.
  1593. static int ge_frombytes_neg_vartime(ge *h, const u8 s[32])
  1594. {
  1595. fe_frombytes(h->Y, s);
  1596. fe_1(h->Z);
  1597. fe_sq (h->T, h->Y); // t = y^2
  1598. fe_mul(h->X, h->T, d ); // x = d*y^2
  1599. fe_sub(h->T, h->T, h->Z); // t = y^2 - 1
  1600. fe_add(h->X, h->X, h->Z); // x = d*y^2 + 1
  1601. fe_mul(h->X, h->T, h->X); // x = (y^2 - 1) * (d*y^2 + 1)
  1602. int is_square = invsqrt(h->X, h->X);
  1603. if (!is_square) {
  1604. return -1; // Not on the curve, abort
  1605. }
  1606. fe_mul(h->X, h->T, h->X); // x = sqrt((y^2 - 1) / (d*y^2 + 1))
  1607. if (fe_isodd(h->X) == (s[31] >> 7)) {
  1608. fe_neg(h->X, h->X);
  1609. }
  1610. fe_mul(h->T, h->X, h->Y);
  1611. return 0;
  1612. }
  1613. static void ge_cache(ge_cached *c, const ge *p)
  1614. {
  1615. fe_add (c->Yp, p->Y, p->X);
  1616. fe_sub (c->Ym, p->Y, p->X);
  1617. fe_copy(c->Z , p->Z );
  1618. fe_mul (c->T2, p->T, D2 );
  1619. }
  1620. // Internal buffers are not wiped! Inputs must not be secret!
  1621. // => Use only to *check* signatures.
  1622. static void ge_add(ge *s, const ge *p, const ge_cached *q)
  1623. {
  1624. fe a, b;
  1625. fe_add(a , p->Y, p->X );
  1626. fe_sub(b , p->Y, p->X );
  1627. fe_mul(a , a , q->Yp);
  1628. fe_mul(b , b , q->Ym);
  1629. fe_add(s->Y, a , b );
  1630. fe_sub(s->X, a , b );
  1631. fe_add(s->Z, p->Z, p->Z );
  1632. fe_mul(s->Z, s->Z, q->Z );
  1633. fe_mul(s->T, p->T, q->T2);
  1634. fe_add(a , s->Z, s->T );
  1635. fe_sub(b , s->Z, s->T );
  1636. fe_mul(s->T, s->X, s->Y);
  1637. fe_mul(s->X, s->X, b );
  1638. fe_mul(s->Y, s->Y, a );
  1639. fe_mul(s->Z, a , b );
  1640. }
  1641. // Internal buffers are not wiped! Inputs must not be secret!
  1642. // => Use only to *check* signatures.
  1643. static void ge_sub(ge *s, const ge *p, const ge_cached *q)
  1644. {
  1645. ge_cached neg;
  1646. fe_copy(neg.Ym, q->Yp);
  1647. fe_copy(neg.Yp, q->Ym);
  1648. fe_copy(neg.Z , q->Z );
  1649. fe_neg (neg.T2, q->T2);
  1650. ge_add(s, p, &neg);
  1651. }
  1652. static void ge_madd(ge *s, const ge *p, const ge_precomp *q, fe a, fe b)
  1653. {
  1654. fe_add(a , p->Y, p->X );
  1655. fe_sub(b , p->Y, p->X );
  1656. fe_mul(a , a , q->Yp);
  1657. fe_mul(b , b , q->Ym);
  1658. fe_add(s->Y, a , b );
  1659. fe_sub(s->X, a , b );
  1660. fe_add(s->Z, p->Z, p->Z );
  1661. fe_mul(s->T, p->T, q->T2);
  1662. fe_add(a , s->Z, s->T );
  1663. fe_sub(b , s->Z, s->T );
  1664. fe_mul(s->T, s->X, s->Y);
  1665. fe_mul(s->X, s->X, b );
  1666. fe_mul(s->Y, s->Y, a );
  1667. fe_mul(s->Z, a , b );
  1668. }
  1669. // Internal buffers are not wiped! Inputs must not be secret!
  1670. // => Use only to *check* signatures.
  1671. static void ge_msub(ge *s, const ge *p, const ge_precomp *q, fe a, fe b)
  1672. {
  1673. ge_precomp neg;
  1674. fe_copy(neg.Ym, q->Yp);
  1675. fe_copy(neg.Yp, q->Ym);
  1676. fe_neg (neg.T2, q->T2);
  1677. ge_madd(s, p, &neg, a, b);
  1678. }
  1679. static void ge_double(ge *s, const ge *p, ge *q)
  1680. {
  1681. fe_sq (q->X, p->X);
  1682. fe_sq (q->Y, p->Y);
  1683. fe_sq (q->Z, p->Z); // qZ = pZ^2
  1684. fe_mul_small(q->Z, q->Z, 2); // qZ = pZ^2 * 2
  1685. fe_add(q->T, p->X, p->Y);
  1686. fe_sq (s->T, q->T);
  1687. fe_add(q->T, q->Y, q->X);
  1688. fe_sub(q->Y, q->Y, q->X);
  1689. fe_sub(q->X, s->T, q->T);
  1690. fe_sub(q->Z, q->Z, q->Y);
  1691. fe_mul(s->X, q->X , q->Z);
  1692. fe_mul(s->Y, q->T , q->Y);
  1693. fe_mul(s->Z, q->Y , q->Z);
  1694. fe_mul(s->T, q->X , q->T);
  1695. }
  1696. // 5-bit signed window in cached format (Niels coordinates, Z=1)
  1697. static const ge_precomp b_window[8] = {
  1698. {{25967493,-14356035,29566456,3660896,-12694345,
  1699. 4014787,27544626,-11754271,-6079156,2047605,},
  1700. {-12545711,934262,-2722910,3049990,-727428,
  1701. 9406986,12720692,5043384,19500929,-15469378,},
  1702. {-8738181,4489570,9688441,-14785194,10184609,
  1703. -12363380,29287919,11864899,-24514362,-4438546,},},
  1704. {{15636291,-9688557,24204773,-7912398,616977,
  1705. -16685262,27787600,-14772189,28944400,-1550024,},
  1706. {16568933,4717097,-11556148,-1102322,15682896,
  1707. -11807043,16354577,-11775962,7689662,11199574,},
  1708. {30464156,-5976125,-11779434,-15670865,23220365,
  1709. 15915852,7512774,10017326,-17749093,-9920357,},},
  1710. {{10861363,11473154,27284546,1981175,-30064349,
  1711. 12577861,32867885,14515107,-15438304,10819380,},
  1712. {4708026,6336745,20377586,9066809,-11272109,
  1713. 6594696,-25653668,12483688,-12668491,5581306,},
  1714. {19563160,16186464,-29386857,4097519,10237984,
  1715. -4348115,28542350,13850243,-23678021,-15815942,},},
  1716. {{5153746,9909285,1723747,-2777874,30523605,
  1717. 5516873,19480852,5230134,-23952439,-15175766,},
  1718. {-30269007,-3463509,7665486,10083793,28475525,
  1719. 1649722,20654025,16520125,30598449,7715701,},
  1720. {28881845,14381568,9657904,3680757,-20181635,
  1721. 7843316,-31400660,1370708,29794553,-1409300,},},
  1722. {{-22518993,-6692182,14201702,-8745502,-23510406,
  1723. 8844726,18474211,-1361450,-13062696,13821877,},
  1724. {-6455177,-7839871,3374702,-4740862,-27098617,
  1725. -10571707,31655028,-7212327,18853322,-14220951,},
  1726. {4566830,-12963868,-28974889,-12240689,-7602672,
  1727. -2830569,-8514358,-10431137,2207753,-3209784,},},
  1728. {{-25154831,-4185821,29681144,7868801,-6854661,
  1729. -9423865,-12437364,-663000,-31111463,-16132436,},
  1730. {25576264,-2703214,7349804,-11814844,16472782,
  1731. 9300885,3844789,15725684,171356,6466918,},
  1732. {23103977,13316479,9739013,-16149481,817875,
  1733. -15038942,8965339,-14088058,-30714912,16193877,},},
  1734. {{-33521811,3180713,-2394130,14003687,-16903474,
  1735. -16270840,17238398,4729455,-18074513,9256800,},
  1736. {-25182317,-4174131,32336398,5036987,-21236817,
  1737. 11360617,22616405,9761698,-19827198,630305,},
  1738. {-13720693,2639453,-24237460,-7406481,9494427,
  1739. -5774029,-6554551,-15960994,-2449256,-14291300,},},
  1740. {{-3151181,-5046075,9282714,6866145,-31907062,
  1741. -863023,-18940575,15033784,25105118,-7894876,},
  1742. {-24326370,15950226,-31801215,-14592823,-11662737,
  1743. -5090925,1573892,-2625887,2198790,-15804619,},
  1744. {-3099351,10324967,-2241613,7453183,-5446979,
  1745. -2735503,-13812022,-16236442,-32461234,-12290683,},},
  1746. };
  1747. // Incremental sliding windows (left to right)
  1748. // Based on Roberto Maria Avanzi[2005]
  1749. typedef struct {
  1750. i16 next_index; // position of the next signed digit
  1751. i8 next_digit; // next signed digit (odd number below 2^window_width)
  1752. u8 next_check; // point at which we must check for a new window
  1753. } slide_ctx;
  1754. static void slide_init(slide_ctx *ctx, const u8 scalar[32])
  1755. {
  1756. // scalar is guaranteed to be below L, either because we checked (s),
  1757. // or because we reduced it modulo L (h_ram). L is under 2^253, so
  1758. // so bits 253 to 255 are guaranteed to be zero. No need to test them.
  1759. //
  1760. // Note however that L is very close to 2^252, so bit 252 is almost
  1761. // always zero. If we were to start at bit 251, the tests wouldn't
  1762. // catch the off-by-one error (constructing one that does would be
  1763. // prohibitively expensive).
  1764. //
  1765. // We should still check bit 252, though.
  1766. int i = 252;
  1767. while (i > 0 && scalar_bit(scalar, i) == 0) {
  1768. i--;
  1769. }
  1770. ctx->next_check = (u8)(i + 1);
  1771. ctx->next_index = -1;
  1772. ctx->next_digit = -1;
  1773. }
  1774. static int slide_step(slide_ctx *ctx, int width, int i, const u8 scalar[32])
  1775. {
  1776. if (i == ctx->next_check) {
  1777. if (scalar_bit(scalar, i) == scalar_bit(scalar, i - 1)) {
  1778. ctx->next_check--;
  1779. } else {
  1780. // compute digit of next window
  1781. int w = MIN(width, i + 1);
  1782. int v = -(scalar_bit(scalar, i) << (w-1));
  1783. FOR_T (int, j, 0, w-1) {
  1784. v += scalar_bit(scalar, i-(w-1)+j) << j;
  1785. }
  1786. v += scalar_bit(scalar, i-w);
  1787. int lsb = v & (~v + 1); // smallest bit of v
  1788. int s = // log2(lsb)
  1789. (((lsb & 0xAA) != 0) << 0) |
  1790. (((lsb & 0xCC) != 0) << 1) |
  1791. (((lsb & 0xF0) != 0) << 2);
  1792. ctx->next_index = (i16)(i-(w-1)+s);
  1793. ctx->next_digit = (i8) (v >> s );
  1794. ctx->next_check -= (u8) w;
  1795. }
  1796. }
  1797. return i == ctx->next_index ? ctx->next_digit: 0;
  1798. }
  1799. #define P_W_WIDTH 3 // Affects the size of the stack
  1800. #define B_W_WIDTH 5 // Affects the size of the binary
  1801. #define P_W_SIZE (1<<(P_W_WIDTH-2))
  1802. int crypto_eddsa_check_equation(const u8 signature[64], const u8 public_key[32],
  1803. const u8 h[32])
  1804. {
  1805. ge minus_A; // -public_key
  1806. ge minus_R; // -first_half_of_signature
  1807. const u8 *s = signature + 32;
  1808. // Check that A and R are on the curve
  1809. // Check that 0 <= S < L (prevents malleability)
  1810. // *Allow* non-cannonical encoding for A and R
  1811. {
  1812. u32 s32[8];
  1813. load32_le_buf(s32, s, 8);
  1814. if (ge_frombytes_neg_vartime(&minus_A, public_key) ||
  1815. ge_frombytes_neg_vartime(&minus_R, signature) ||
  1816. is_above_l(s32)) {
  1817. return -1;
  1818. }
  1819. }
  1820. // look-up table for minus_A
  1821. ge_cached lutA[P_W_SIZE];
  1822. {
  1823. ge minus_A2, tmp;
  1824. ge_double(&minus_A2, &minus_A, &tmp);
  1825. ge_cache(&lutA[0], &minus_A);
  1826. FOR (i, 1, P_W_SIZE) {
  1827. ge_add(&tmp, &minus_A2, &lutA[i-1]);
  1828. ge_cache(&lutA[i], &tmp);
  1829. }
  1830. }
  1831. // sum = [s]B - [h]A
  1832. // Merged double and add ladder, fused with sliding
  1833. slide_ctx h_slide; slide_init(&h_slide, h);
  1834. slide_ctx s_slide; slide_init(&s_slide, s);
  1835. int i = MAX(h_slide.next_check, s_slide.next_check);
  1836. ge *sum = &minus_A; // reuse minus_A for the sum
  1837. ge_zero(sum);
  1838. while (i >= 0) {
  1839. ge tmp;
  1840. ge_double(sum, sum, &tmp);
  1841. int h_digit = slide_step(&h_slide, P_W_WIDTH, i, h);
  1842. int s_digit = slide_step(&s_slide, B_W_WIDTH, i, s);
  1843. if (h_digit > 0) { ge_add(sum, sum, &lutA[ h_digit / 2]); }
  1844. if (h_digit < 0) { ge_sub(sum, sum, &lutA[-h_digit / 2]); }
  1845. fe t1, t2;
  1846. if (s_digit > 0) { ge_madd(sum, sum, b_window + s_digit/2, t1, t2); }
  1847. if (s_digit < 0) { ge_msub(sum, sum, b_window + -s_digit/2, t1, t2); }
  1848. i--;
  1849. }
  1850. // Compare [8](sum-R) and the zero point
  1851. // The multiplication by 8 eliminates any low-order component
  1852. // and ensures consistency with batched verification.
  1853. ge_cached cached;
  1854. u8 check[32];
  1855. static const u8 zero_point[32] = {1}; // Point of order 1
  1856. ge_cache(&cached, &minus_R);
  1857. ge_add(sum, sum, &cached);
  1858. ge_double(sum, sum, &minus_R); // reuse minus_R as temporary
  1859. ge_double(sum, sum, &minus_R); // reuse minus_R as temporary
  1860. ge_double(sum, sum, &minus_R); // reuse minus_R as temporary
  1861. ge_tobytes(check, sum);
  1862. return crypto_verify32(check, zero_point);
  1863. }
  1864. // 5-bit signed comb in cached format (Niels coordinates, Z=1)
  1865. static const ge_precomp b_comb_low[8] = {
  1866. {{-6816601,-2324159,-22559413,124364,18015490,
  1867. 8373481,19993724,1979872,-18549925,9085059,},
  1868. {10306321,403248,14839893,9633706,8463310,
  1869. -8354981,-14305673,14668847,26301366,2818560,},
  1870. {-22701500,-3210264,-13831292,-2927732,-16326337,
  1871. -14016360,12940910,177905,12165515,-2397893,},},
  1872. {{-12282262,-7022066,9920413,-3064358,-32147467,
  1873. 2927790,22392436,-14852487,2719975,16402117,},
  1874. {-7236961,-4729776,2685954,-6525055,-24242706,
  1875. -15940211,-6238521,14082855,10047669,12228189,},
  1876. {-30495588,-12893761,-11161261,3539405,-11502464,
  1877. 16491580,-27286798,-15030530,-7272871,-15934455,},},
  1878. {{17650926,582297,-860412,-187745,-12072900,
  1879. -10683391,-20352381,15557840,-31072141,-5019061,},
  1880. {-6283632,-2259834,-4674247,-4598977,-4089240,
  1881. 12435688,-31278303,1060251,6256175,10480726,},
  1882. {-13871026,2026300,-21928428,-2741605,-2406664,
  1883. -8034988,7355518,15733500,-23379862,7489131,},},
  1884. {{6883359,695140,23196907,9644202,-33430614,
  1885. 11354760,-20134606,6388313,-8263585,-8491918,},
  1886. {-7716174,-13605463,-13646110,14757414,-19430591,
  1887. -14967316,10359532,-11059670,-21935259,12082603,},
  1888. {-11253345,-15943946,10046784,5414629,24840771,
  1889. 8086951,-6694742,9868723,15842692,-16224787,},},
  1890. {{9639399,11810955,-24007778,-9320054,3912937,
  1891. -9856959,996125,-8727907,-8919186,-14097242,},
  1892. {7248867,14468564,25228636,-8795035,14346339,
  1893. 8224790,6388427,-7181107,6468218,-8720783,},
  1894. {15513115,15439095,7342322,-10157390,18005294,
  1895. -7265713,2186239,4884640,10826567,7135781,},},
  1896. {{-14204238,5297536,-5862318,-6004934,28095835,
  1897. 4236101,-14203318,1958636,-16816875,3837147,},
  1898. {-5511166,-13176782,-29588215,12339465,15325758,
  1899. -15945770,-8813185,11075932,-19608050,-3776283,},
  1900. {11728032,9603156,-4637821,-5304487,-7827751,
  1901. 2724948,31236191,-16760175,-7268616,14799772,},},
  1902. {{-28842672,4840636,-12047946,-9101456,-1445464,
  1903. 381905,-30977094,-16523389,1290540,12798615,},
  1904. {27246947,-10320914,14792098,-14518944,5302070,
  1905. -8746152,-3403974,-4149637,-27061213,10749585,},
  1906. {25572375,-6270368,-15353037,16037944,1146292,
  1907. 32198,23487090,9585613,24714571,-1418265,},},
  1908. {{19844825,282124,-17583147,11004019,-32004269,
  1909. -2716035,6105106,-1711007,-21010044,14338445,},
  1910. {8027505,8191102,-18504907,-12335737,25173494,
  1911. -5923905,15446145,7483684,-30440441,10009108,},
  1912. {-14134701,-4174411,10246585,-14677495,33553567,
  1913. -14012935,23366126,15080531,-7969992,7663473,},},
  1914. };
  1915. static const ge_precomp b_comb_high[8] = {
  1916. {{33055887,-4431773,-521787,6654165,951411,
  1917. -6266464,-5158124,6995613,-5397442,-6985227,},
  1918. {4014062,6967095,-11977872,3960002,8001989,
  1919. 5130302,-2154812,-1899602,-31954493,-16173976,},
  1920. {16271757,-9212948,23792794,731486,-25808309,
  1921. -3546396,6964344,-4767590,10976593,10050757,},},
  1922. {{2533007,-4288439,-24467768,-12387405,-13450051,
  1923. 14542280,12876301,13893535,15067764,8594792,},
  1924. {20073501,-11623621,3165391,-13119866,13188608,
  1925. -11540496,-10751437,-13482671,29588810,2197295,},
  1926. {-1084082,11831693,6031797,14062724,14748428,
  1927. -8159962,-20721760,11742548,31368706,13161200,},},
  1928. {{2050412,-6457589,15321215,5273360,25484180,
  1929. 124590,-18187548,-7097255,-6691621,-14604792,},
  1930. {9938196,2162889,-6158074,-1711248,4278932,
  1931. -2598531,-22865792,-7168500,-24323168,11746309,},
  1932. {-22691768,-14268164,5965485,9383325,20443693,
  1933. 5854192,28250679,-1381811,-10837134,13717818,},},
  1934. {{-8495530,16382250,9548884,-4971523,-4491811,
  1935. -3902147,6182256,-12832479,26628081,10395408,},
  1936. {27329048,-15853735,7715764,8717446,-9215518,
  1937. -14633480,28982250,-5668414,4227628,242148,},
  1938. {-13279943,-7986904,-7100016,8764468,-27276630,
  1939. 3096719,29678419,-9141299,3906709,11265498,},},
  1940. {{11918285,15686328,-17757323,-11217300,-27548967,
  1941. 4853165,-27168827,6807359,6871949,-1075745,},
  1942. {-29002610,13984323,-27111812,-2713442,28107359,
  1943. -13266203,6155126,15104658,3538727,-7513788,},
  1944. {14103158,11233913,-33165269,9279850,31014152,
  1945. 4335090,-1827936,4590951,13960841,12787712,},},
  1946. {{1469134,-16738009,33411928,13942824,8092558,
  1947. -8778224,-11165065,1437842,22521552,-2792954,},
  1948. {31352705,-4807352,-25327300,3962447,12541566,
  1949. -9399651,-27425693,7964818,-23829869,5541287,},
  1950. {-25732021,-6864887,23848984,3039395,-9147354,
  1951. 6022816,-27421653,10590137,25309915,-1584678,},},
  1952. {{-22951376,5048948,31139401,-190316,-19542447,
  1953. -626310,-17486305,-16511925,-18851313,-12985140,},
  1954. {-9684890,14681754,30487568,7717771,-10829709,
  1955. 9630497,30290549,-10531496,-27798994,-13812825,},
  1956. {5827835,16097107,-24501327,12094619,7413972,
  1957. 11447087,28057551,-1793987,-14056981,4359312,},},
  1958. {{26323183,2342588,-21887793,-1623758,-6062284,
  1959. 2107090,-28724907,9036464,-19618351,-13055189,},
  1960. {-29697200,14829398,-4596333,14220089,-30022969,
  1961. 2955645,12094100,-13693652,-5941445,7047569,},
  1962. {-3201977,14413268,-12058324,-16417589,-9035655,
  1963. -7224648,9258160,1399236,30397584,-5684634,},},
  1964. };
  1965. static void lookup_add(ge *p, ge_precomp *tmp_c, fe tmp_a, fe tmp_b,
  1966. const ge_precomp comb[8], const u8 scalar[32], int i)
  1967. {
  1968. u8 teeth = (u8)((scalar_bit(scalar, i) ) +
  1969. (scalar_bit(scalar, i + 32) << 1) +
  1970. (scalar_bit(scalar, i + 64) << 2) +
  1971. (scalar_bit(scalar, i + 96) << 3));
  1972. u8 high = teeth >> 3;
  1973. u8 index = (teeth ^ (high - 1)) & 7;
  1974. FOR (j, 0, 8) {
  1975. i32 select = 1 & (((j ^ index) - 1) >> 8);
  1976. fe_ccopy(tmp_c->Yp, comb[j].Yp, select);
  1977. fe_ccopy(tmp_c->Ym, comb[j].Ym, select);
  1978. fe_ccopy(tmp_c->T2, comb[j].T2, select);
  1979. }
  1980. fe_neg(tmp_a, tmp_c->T2);
  1981. fe_cswap(tmp_c->T2, tmp_a , high ^ 1);
  1982. fe_cswap(tmp_c->Yp, tmp_c->Ym, high ^ 1);
  1983. ge_madd(p, p, tmp_c, tmp_a, tmp_b);
  1984. }
  1985. // p = [scalar]B, where B is the base point
  1986. static void ge_scalarmult_base(ge *p, const u8 scalar[32])
  1987. {
  1988. // twin 4-bits signed combs, from Mike Hamburg's
  1989. // Fast and compact elliptic-curve cryptography (2012)
  1990. // 1 / 2 modulo L
  1991. static const u8 half_mod_L[32] = {
  1992. 247,233,122,46,141,49,9,44,107,206,123,81,239,124,111,10,
  1993. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,
  1994. };
  1995. // (2^256 - 1) / 2 modulo L
  1996. static const u8 half_ones[32] = {
  1997. 142,74,204,70,186,24,118,107,184,231,190,57,250,173,119,99,
  1998. 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,
  1999. };
  2000. // All bits set form: 1 means 1, 0 means -1
  2001. u8 s_scalar[32];
  2002. crypto_eddsa_mul_add(s_scalar, scalar, half_mod_L, half_ones);
  2003. // Double and add ladder
  2004. fe tmp_a, tmp_b; // temporaries for addition
  2005. ge_precomp tmp_c; // temporary for comb lookup
  2006. ge tmp_d; // temporary for doubling
  2007. fe_1(tmp_c.Yp);
  2008. fe_1(tmp_c.Ym);
  2009. fe_0(tmp_c.T2);
  2010. // Save a double on the first iteration
  2011. ge_zero(p);
  2012. lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, 31);
  2013. lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, 31+128);
  2014. // Regular double & add for the rest
  2015. for (int i = 30; i >= 0; i--) {
  2016. ge_double(p, p, &tmp_d);
  2017. lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, i);
  2018. lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, i+128);
  2019. }
  2020. // Note: we could save one addition at the end if we assumed the
  2021. // scalar fit in 252 bits. Which it does in practice if it is
  2022. // selected at random. However, non-random, non-hashed scalars
  2023. // *can* overflow 252 bits in practice. Better account for that
  2024. // than leaving that kind of subtle corner case.
  2025. WIPE_BUFFER(tmp_a); WIPE_CTX(&tmp_d);
  2026. WIPE_BUFFER(tmp_b); WIPE_CTX(&tmp_c);
  2027. WIPE_BUFFER(s_scalar);
  2028. }
  2029. void crypto_eddsa_scalarbase(u8 point[32], const u8 scalar[32])
  2030. {
  2031. ge P;
  2032. ge_scalarmult_base(&P, scalar);
  2033. ge_tobytes(point, &P);
  2034. WIPE_CTX(&P);
  2035. }
  2036. void crypto_eddsa_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32])
  2037. {
  2038. // To allow overlaps, observable writes happen in this order:
  2039. // 1. seed
  2040. // 2. secret_key
  2041. // 3. public_key
  2042. u8 a[64];
  2043. COPY(a, seed, 32);
  2044. crypto_wipe(seed, 32);
  2045. COPY(secret_key, a, 32);
  2046. crypto_blake2b(a, 64, a, 32);
  2047. crypto_eddsa_trim_scalar(a, a);
  2048. crypto_eddsa_scalarbase(secret_key + 32, a);
  2049. COPY(public_key, secret_key + 32, 32);
  2050. WIPE_BUFFER(a);
  2051. }
  2052. static void hash_reduce(u8 h[32],
  2053. const u8 *a, size_t a_size,
  2054. const u8 *b, size_t b_size,
  2055. const u8 *c, size_t c_size)
  2056. {
  2057. u8 hash[64];
  2058. crypto_blake2b_ctx ctx;
  2059. crypto_blake2b_init (&ctx, 64);
  2060. crypto_blake2b_update(&ctx, a, a_size);
  2061. crypto_blake2b_update(&ctx, b, b_size);
  2062. crypto_blake2b_update(&ctx, c, c_size);
  2063. crypto_blake2b_final (&ctx, hash);
  2064. crypto_eddsa_reduce(h, hash);
  2065. }
  2066. // Digital signature of a message with from a secret key.
  2067. //
  2068. // The secret key comprises two parts:
  2069. // - The seed that generates the key (secret_key[ 0..31])
  2070. // - The public key (secret_key[32..63])
  2071. //
  2072. // The seed and the public key are bundled together to make sure users
  2073. // don't use mismatched seeds and public keys, which would instantly
  2074. // leak the secret scalar and allow forgeries (allowing this to happen
  2075. // has resulted in critical vulnerabilities in the wild).
  2076. //
  2077. // The seed is hashed to derive the secret scalar and a secret prefix.
  2078. // The sole purpose of the prefix is to generate a secret random nonce.
  2079. // The properties of that nonce must be as follows:
  2080. // - Unique: we need a different one for each message.
  2081. // - Secret: third parties must not be able to predict it.
  2082. // - Random: any detectable bias would break all security.
  2083. //
  2084. // There are two ways to achieve these properties. The obvious one is
  2085. // to simply generate a random number. Here that would be a parameter
  2086. // (Monocypher doesn't have an RNG). It works, but then users may reuse
  2087. // the nonce by accident, which _also_ leaks the secret scalar and
  2088. // allows forgeries. This has happened in the wild too.
  2089. //
  2090. // This is no good, so instead we generate that nonce deterministically
  2091. // by reducing modulo L a hash of the secret prefix and the message.
  2092. // The secret prefix makes the nonce unpredictable, the message makes it
  2093. // unique, and the hash/reduce removes all bias.
  2094. //
  2095. // The cost of that safety is hashing the message twice. If that cost
  2096. // is unacceptable, there are two alternatives:
  2097. //
  2098. // - Signing a hash of the message instead of the message itself. This
  2099. // is fine as long as the hash is collision resistant. It is not
  2100. // compatible with existing "pure" signatures, but at least it's safe.
  2101. //
  2102. // - Using a random nonce. Please exercise **EXTREME CAUTION** if you
  2103. // ever do that. It is absolutely **critical** that the nonce is
  2104. // really an unbiased random number between 0 and L-1, never reused,
  2105. // and wiped immediately.
  2106. //
  2107. // To lower the likelihood of complete catastrophe if the RNG is
  2108. // either flawed or misused, you can hash the RNG output together with
  2109. // the secret prefix and the beginning of the message, and use the
  2110. // reduction of that hash instead of the RNG output itself. It's not
  2111. // foolproof (you'd need to hash the whole message) but it helps.
  2112. //
  2113. // Signing a message involves the following operations:
  2114. //
  2115. // scalar, prefix = HASH(secret_key)
  2116. // r = HASH(prefix || message) % L
  2117. // R = [r]B
  2118. // h = HASH(R || public_key || message) % L
  2119. // S = ((h * a) + r) % L
  2120. // signature = R || S
  2121. void crypto_eddsa_sign(u8 signature [64], const u8 secret_key[64],
  2122. const u8 *message, size_t message_size)
  2123. {
  2124. u8 a[64]; // secret scalar and prefix
  2125. u8 r[32]; // secret deterministic "random" nonce
  2126. u8 h[32]; // publically verifiable hash of the message (not wiped)
  2127. u8 R[32]; // first half of the signature (allows overlapping inputs)
  2128. crypto_blake2b(a, 64, secret_key, 32);
  2129. crypto_eddsa_trim_scalar(a, a);
  2130. hash_reduce(r, a + 32, 32, message, message_size, 0, 0);
  2131. crypto_eddsa_scalarbase(R, r);
  2132. hash_reduce(h, R, 32, secret_key + 32, 32, message, message_size);
  2133. COPY(signature, R, 32);
  2134. crypto_eddsa_mul_add(signature + 32, h, a, r);
  2135. WIPE_BUFFER(a);
  2136. WIPE_BUFFER(r);
  2137. }
  2138. // To check the signature R, S of the message M with the public key A,
  2139. // there are 3 steps:
  2140. //
  2141. // compute h = HASH(R || A || message) % L
  2142. // check that A is on the curve.
  2143. // check that R == [s]B - [h]A
  2144. //
  2145. // The last two steps are done in crypto_eddsa_check_equation()
  2146. int crypto_eddsa_check(const u8 signature[64], const u8 public_key[32],
  2147. const u8 *message, size_t message_size)
  2148. {
  2149. u8 h[32];
  2150. hash_reduce(h, signature, 32, public_key, 32, message, message_size);
  2151. return crypto_eddsa_check_equation(signature, public_key, h);
  2152. }
  2153. /////////////////////////
  2154. /// EdDSA <--> X25519 ///
  2155. /////////////////////////
  2156. void crypto_eddsa_to_x25519(u8 x25519[32], const u8 eddsa[32])
  2157. {
  2158. // (u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)
  2159. // Only converting y to u, the sign of x is ignored.
  2160. fe t1, t2;
  2161. fe_frombytes(t2, eddsa);
  2162. fe_add(t1, fe_one, t2);
  2163. fe_sub(t2, fe_one, t2);
  2164. fe_invert(t2, t2);
  2165. fe_mul(t1, t1, t2);
  2166. fe_tobytes(x25519, t1);
  2167. WIPE_BUFFER(t1);
  2168. WIPE_BUFFER(t2);
  2169. }
  2170. void crypto_x25519_to_eddsa(u8 eddsa[32], const u8 x25519[32])
  2171. {
  2172. // (x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))
  2173. // Only converting u to y, x is assumed positive.
  2174. fe t1, t2;
  2175. fe_frombytes(t2, x25519);
  2176. fe_sub(t1, t2, fe_one);
  2177. fe_add(t2, t2, fe_one);
  2178. fe_invert(t2, t2);
  2179. fe_mul(t1, t1, t2);
  2180. fe_tobytes(eddsa, t1);
  2181. WIPE_BUFFER(t1);
  2182. WIPE_BUFFER(t2);
  2183. }
  2184. /////////////////////////////////////////////
  2185. /// Dirty ephemeral public key generation ///
  2186. /////////////////////////////////////////////
  2187. // Those functions generates a public key, *without* clearing the
  2188. // cofactor. Sending that key over the network leaks 3 bits of the
  2189. // private key. Use only to generate ephemeral keys that will be hidden
  2190. // with crypto_curve_to_hidden().
  2191. //
  2192. // The public key is otherwise compatible with crypto_x25519(), which
  2193. // properly clears the cofactor.
  2194. //
  2195. // Note that the distribution of the resulting public keys is almost
  2196. // uniform. Flipping the sign of the v coordinate (not provided by this
  2197. // function), covers the entire key space almost perfectly, where
  2198. // "almost" means a 2^-128 bias (undetectable). This uniformity is
  2199. // needed to ensure the proper randomness of the resulting
  2200. // representatives (once we apply crypto_curve_to_hidden()).
  2201. //
  2202. // Recall that Curve25519 has order C = 2^255 + e, with e < 2^128 (not
  2203. // to be confused with the prime order of the main subgroup, L, which is
  2204. // 8 times less than that).
  2205. //
  2206. // Generating all points would require us to multiply a point of order C
  2207. // (the base point plus any point of order 8) by all scalars from 0 to
  2208. // C-1. Clamping limits us to scalars between 2^254 and 2^255 - 1. But
  2209. // by negating the resulting point at random, we also cover scalars from
  2210. // -2^255 + 1 to -2^254 (which modulo C is congruent to e+1 to 2^254 + e).
  2211. //
  2212. // In practice:
  2213. // - Scalars from 0 to e + 1 are never generated
  2214. // - Scalars from 2^255 to 2^255 + e are never generated
  2215. // - Scalars from 2^254 + 1 to 2^254 + e are generated twice
  2216. //
  2217. // Since e < 2^128, detecting this bias requires observing over 2^100
  2218. // representatives from a given source (this will never happen), *and*
  2219. // recovering enough of the private key to determine that they do, or do
  2220. // not, belong to the biased set (this practically requires solving
  2221. // discrete logarithm, which is conjecturally intractable).
  2222. //
  2223. // In practice, this means the bias is impossible to detect.
  2224. // s + (x*L) % 8*L
  2225. // Guaranteed to fit in 256 bits iff s fits in 255 bits.
  2226. // L < 2^253
  2227. // x%8 < 2^3
  2228. // L * (x%8) < 2^255
  2229. // s < 2^255
  2230. // s + L * (x%8) < 2^256
  2231. static void add_xl(u8 s[32], u8 x)
  2232. {
  2233. u64 mod8 = x & 7;
  2234. u64 carry = 0;
  2235. FOR (i , 0, 8) {
  2236. carry = carry + load32_le(s + 4*i) + L[i] * mod8;
  2237. store32_le(s + 4*i, (u32)carry);
  2238. carry >>= 32;
  2239. }
  2240. }
  2241. // "Small" dirty ephemeral key.
  2242. // Use if you need to shrink the size of the binary, and can afford to
  2243. // slow down by a factor of two (compared to the fast version)
  2244. //
  2245. // This version works by decoupling the cofactor from the main factor.
  2246. //
  2247. // - The trimmed scalar determines the main factor
  2248. // - The clamped bits of the scalar determine the cofactor.
  2249. //
  2250. // Cofactor and main factor are combined into a single scalar, which is
  2251. // then multiplied by a point of order 8*L (unlike the base point, which
  2252. // has prime order). That "dirty" base point is the addition of the
  2253. // regular base point (9), and a point of order 8.
  2254. void crypto_x25519_dirty_small(u8 public_key[32], const u8 secret_key[32])
  2255. {
  2256. // Base point of order 8*L
  2257. // Raw scalar multiplication with it does not clear the cofactor,
  2258. // and the resulting public key will reveal 3 bits of the scalar.
  2259. //
  2260. // The low order component of this base point has been chosen
  2261. // to yield the same results as crypto_x25519_dirty_fast().
  2262. static const u8 dirty_base_point[32] = {
  2263. 0xd8, 0x86, 0x1a, 0xa2, 0x78, 0x7a, 0xd9, 0x26,
  2264. 0x8b, 0x74, 0x74, 0xb6, 0x82, 0xe3, 0xbe, 0xc3,
  2265. 0xce, 0x36, 0x9a, 0x1e, 0x5e, 0x31, 0x47, 0xa2,
  2266. 0x6d, 0x37, 0x7c, 0xfd, 0x20, 0xb5, 0xdf, 0x75,
  2267. };
  2268. // separate the main factor & the cofactor of the scalar
  2269. u8 scalar[32];
  2270. crypto_eddsa_trim_scalar(scalar, secret_key);
  2271. // Separate the main factor and the cofactor
  2272. //
  2273. // The scalar is trimmed, so its cofactor is cleared. The three
  2274. // least significant bits however still have a main factor. We must
  2275. // remove it for X25519 compatibility.
  2276. //
  2277. // cofactor = lsb * L (modulo 8*L)
  2278. // combined = scalar + cofactor (modulo 8*L)
  2279. add_xl(scalar, secret_key[0]);
  2280. scalarmult(public_key, scalar, dirty_base_point, 256);
  2281. WIPE_BUFFER(scalar);
  2282. }
  2283. // Select low order point
  2284. // We're computing the [cofactor]lop scalar multiplication, where:
  2285. //
  2286. // cofactor = tweak & 7.
  2287. // lop = (lop_x, lop_y)
  2288. // lop_x = sqrt((sqrt(d + 1) + 1) / d)
  2289. // lop_y = -lop_x * sqrtm1
  2290. //
  2291. // The low order point has order 8. There are 4 such points. We've
  2292. // chosen the one whose both coordinates are positive (below p/2).
  2293. // The 8 low order points are as follows:
  2294. //
  2295. // [0]lop = ( 0 , 1 )
  2296. // [1]lop = ( lop_x , lop_y)
  2297. // [2]lop = ( sqrt(-1), -0 )
  2298. // [3]lop = ( lop_x , -lop_y)
  2299. // [4]lop = (-0 , -1 )
  2300. // [5]lop = (-lop_x , -lop_y)
  2301. // [6]lop = (-sqrt(-1), 0 )
  2302. // [7]lop = (-lop_x , lop_y)
  2303. //
  2304. // The x coordinate is either 0, sqrt(-1), lop_x, or their opposite.
  2305. // The y coordinate is either 0, -1 , lop_y, or their opposite.
  2306. // The pattern for both is the same, except for a rotation of 2 (modulo 8)
  2307. //
  2308. // This helper function captures the pattern, and we can use it thus:
  2309. //
  2310. // select_lop(x, lop_x, sqrtm1, cofactor);
  2311. // select_lop(y, lop_y, fe_one, cofactor + 2);
  2312. //
  2313. // This is faster than an actual scalar multiplication,
  2314. // and requires less code than naive constant time look up.
  2315. static void select_lop(fe out, const fe x, const fe k, u8 cofactor)
  2316. {
  2317. fe tmp;
  2318. fe_0(out);
  2319. fe_ccopy(out, k , (cofactor >> 1) & 1); // bit 1
  2320. fe_ccopy(out, x , (cofactor >> 0) & 1); // bit 0
  2321. fe_neg (tmp, out);
  2322. fe_ccopy(out, tmp, (cofactor >> 2) & 1); // bit 2
  2323. WIPE_BUFFER(tmp);
  2324. }
  2325. // "Fast" dirty ephemeral key
  2326. // We use this one by default.
  2327. //
  2328. // This version works by performing a regular scalar multiplication,
  2329. // then add a low order point. The scalar multiplication is done in
  2330. // Edwards space for more speed (*2 compared to the "small" version).
  2331. // The cost is a bigger binary for programs that don't also sign messages.
  2332. void crypto_x25519_dirty_fast(u8 public_key[32], const u8 secret_key[32])
  2333. {
  2334. // Compute clean scalar multiplication
  2335. u8 scalar[32];
  2336. ge pk;
  2337. crypto_eddsa_trim_scalar(scalar, secret_key);
  2338. ge_scalarmult_base(&pk, scalar);
  2339. // Compute low order point
  2340. fe t1, t2;
  2341. select_lop(t1, lop_x, sqrtm1, secret_key[0]);
  2342. select_lop(t2, lop_y, fe_one, secret_key[0] + 2);
  2343. ge_precomp low_order_point;
  2344. fe_add(low_order_point.Yp, t2, t1);
  2345. fe_sub(low_order_point.Ym, t2, t1);
  2346. fe_mul(low_order_point.T2, t2, t1);
  2347. fe_mul(low_order_point.T2, low_order_point.T2, D2);
  2348. // Add low order point to the public key
  2349. ge_madd(&pk, &pk, &low_order_point, t1, t2);
  2350. // Convert to Montgomery u coordinate (we ignore the sign)
  2351. fe_add(t1, pk.Z, pk.Y);
  2352. fe_sub(t2, pk.Z, pk.Y);
  2353. fe_invert(t2, t2);
  2354. fe_mul(t1, t1, t2);
  2355. fe_tobytes(public_key, t1);
  2356. WIPE_BUFFER(t1); WIPE_CTX(&pk);
  2357. WIPE_BUFFER(t2); WIPE_CTX(&low_order_point);
  2358. WIPE_BUFFER(scalar);
  2359. }
  2360. ///////////////////
  2361. /// Elligator 2 ///
  2362. ///////////////////
  2363. static const fe A = {486662};
  2364. // Elligator direct map
  2365. //
  2366. // Computes the point corresponding to a representative, encoded in 32
  2367. // bytes (little Endian). Since positive representatives fits in 254
  2368. // bits, The two most significant bits are ignored.
  2369. //
  2370. // From the paper:
  2371. // w = -A / (fe(1) + non_square * r^2)
  2372. // e = chi(w^3 + A*w^2 + w)
  2373. // u = e*w - (fe(1)-e)*(A//2)
  2374. // v = -e * sqrt(u^3 + A*u^2 + u)
  2375. //
  2376. // We ignore v because we don't need it for X25519 (the Montgomery
  2377. // ladder only uses u).
  2378. //
  2379. // Note that e is either 0, 1 or -1
  2380. // if e = 0 u = 0 and v = 0
  2381. // if e = 1 u = w
  2382. // if e = -1 u = -w - A = w * non_square * r^2
  2383. //
  2384. // Let r1 = non_square * r^2
  2385. // Let r2 = 1 + r1
  2386. // Note that r2 cannot be zero, -1/non_square is not a square.
  2387. // We can (tediously) verify that:
  2388. // w^3 + A*w^2 + w = (A^2*r1 - r2^2) * A / r2^3
  2389. // Therefore:
  2390. // chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3))
  2391. // chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * 1
  2392. // chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * chi(r2^6)
  2393. // chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3) * r2^6)
  2394. // chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * A * r2^3)
  2395. // Corollary:
  2396. // e = 1 if (A^2*r1 - r2^2) * A * r2^3) is a non-zero square
  2397. // e = -1 if (A^2*r1 - r2^2) * A * r2^3) is not a square
  2398. // Note that w^3 + A*w^2 + w (and therefore e) can never be zero:
  2399. // w^3 + A*w^2 + w = w * (w^2 + A*w + 1)
  2400. // w^3 + A*w^2 + w = w * (w^2 + A*w + A^2/4 - A^2/4 + 1)
  2401. // w^3 + A*w^2 + w = w * (w + A/2)^2 - A^2/4 + 1)
  2402. // which is zero only if:
  2403. // w = 0 (impossible)
  2404. // (w + A/2)^2 = A^2/4 - 1 (impossible, because A^2/4-1 is not a square)
  2405. //
  2406. // Let isr = invsqrt((A^2*r1 - r2^2) * A * r2^3)
  2407. // isr = sqrt(1 / ((A^2*r1 - r2^2) * A * r2^3)) if e = 1
  2408. // isr = sqrt(sqrt(-1) / ((A^2*r1 - r2^2) * A * r2^3)) if e = -1
  2409. //
  2410. // if e = 1
  2411. // let u1 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2
  2412. // u1 = w
  2413. // u1 = u
  2414. //
  2415. // if e = -1
  2416. // let ufactor = -non_square * sqrt(-1) * r^2
  2417. // let vfactor = sqrt(ufactor)
  2418. // let u2 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2 * ufactor
  2419. // u2 = w * -1 * -non_square * r^2
  2420. // u2 = w * non_square * r^2
  2421. // u2 = u
  2422. void crypto_elligator_map(u8 curve[32], const u8 hidden[32])
  2423. {
  2424. fe r, u, t1, t2, t3;
  2425. fe_frombytes_mask(r, hidden, 2); // r is encoded in 254 bits.
  2426. fe_sq(r, r);
  2427. fe_add(t1, r, r);
  2428. fe_add(u, t1, fe_one);
  2429. fe_sq (t2, u);
  2430. fe_mul(t3, A2, t1);
  2431. fe_sub(t3, t3, t2);
  2432. fe_mul(t3, t3, A);
  2433. fe_mul(t1, t2, u);
  2434. fe_mul(t1, t3, t1);
  2435. int is_square = invsqrt(t1, t1);
  2436. fe_mul(u, r, ufactor);
  2437. fe_ccopy(u, fe_one, is_square);
  2438. fe_sq (t1, t1);
  2439. fe_mul(u, u, A);
  2440. fe_mul(u, u, t3);
  2441. fe_mul(u, u, t2);
  2442. fe_mul(u, u, t1);
  2443. fe_neg(u, u);
  2444. fe_tobytes(curve, u);
  2445. WIPE_BUFFER(t1); WIPE_BUFFER(r);
  2446. WIPE_BUFFER(t2); WIPE_BUFFER(u);
  2447. WIPE_BUFFER(t3);
  2448. }
  2449. // Elligator inverse map
  2450. //
  2451. // Computes the representative of a point, if possible. If not, it does
  2452. // nothing and returns -1. Note that the success of the operation
  2453. // depends only on the point (more precisely its u coordinate). The
  2454. // tweak parameter is used only upon success
  2455. //
  2456. // The tweak should be a random byte. Beyond that, its contents are an
  2457. // implementation detail. Currently, the tweak comprises:
  2458. // - Bit 1 : sign of the v coordinate (0 if positive, 1 if negative)
  2459. // - Bit 2-5: not used
  2460. // - Bits 6-7: random padding
  2461. //
  2462. // From the paper:
  2463. // Let sq = -non_square * u * (u+A)
  2464. // if sq is not a square, or u = -A, there is no mapping
  2465. // Assuming there is a mapping:
  2466. // if v is positive: r = sqrt(-u / (non_square * (u+A)))
  2467. // if v is negative: r = sqrt(-(u+A) / (non_square * u ))
  2468. //
  2469. // We compute isr = invsqrt(-non_square * u * (u+A))
  2470. // if it wasn't a square, abort.
  2471. // else, isr = sqrt(-1 / (non_square * u * (u+A))
  2472. //
  2473. // If v is positive, we return isr * u:
  2474. // isr * u = sqrt(-1 / (non_square * u * (u+A)) * u
  2475. // isr * u = sqrt(-u / (non_square * (u+A))
  2476. //
  2477. // If v is negative, we return isr * (u+A):
  2478. // isr * (u+A) = sqrt(-1 / (non_square * u * (u+A)) * (u+A)
  2479. // isr * (u+A) = sqrt(-(u+A) / (non_square * u)
  2480. int crypto_elligator_rev(u8 hidden[32], const u8 public_key[32], u8 tweak)
  2481. {
  2482. fe t1, t2, t3;
  2483. fe_frombytes(t1, public_key); // t1 = u
  2484. fe_add(t2, t1, A); // t2 = u + A
  2485. fe_mul(t3, t1, t2);
  2486. fe_mul_small(t3, t3, -2);
  2487. int is_square = invsqrt(t3, t3); // t3 = sqrt(-1 / non_square * u * (u+A))
  2488. if (is_square) {
  2489. // The only variable time bit. This ultimately reveals how many
  2490. // tries it took us to find a representable key.
  2491. // This does not affect security as long as we try keys at random.
  2492. fe_ccopy (t1, t2, tweak & 1); // multiply by u if v is positive,
  2493. fe_mul (t3, t1, t3); // multiply by u+A otherwise
  2494. fe_mul_small(t1, t3, 2);
  2495. fe_neg (t2, t3);
  2496. fe_ccopy (t3, t2, fe_isodd(t1));
  2497. fe_tobytes(hidden, t3);
  2498. // Pad with two random bits
  2499. hidden[31] |= tweak & 0xc0;
  2500. }
  2501. WIPE_BUFFER(t1);
  2502. WIPE_BUFFER(t2);
  2503. WIPE_BUFFER(t3);
  2504. return is_square - 1;
  2505. }
  2506. void crypto_elligator_key_pair(u8 hidden[32], u8 secret_key[32], u8 seed[32])
  2507. {
  2508. u8 pk [32]; // public key
  2509. u8 buf[64]; // seed + representative
  2510. COPY(buf + 32, seed, 32);
  2511. do {
  2512. crypto_chacha20_djb(buf, 0, 64, buf+32, zero, 0);
  2513. crypto_x25519_dirty_fast(pk, buf); // or the "small" version
  2514. } while(crypto_elligator_rev(buf+32, pk, buf[32]));
  2515. // Note that the return value of crypto_elligator_rev() is
  2516. // independent from its tweak parameter.
  2517. // Therefore, buf[32] is not actually reused. Either we loop one
  2518. // more time and buf[32] is used for the new seed, or we succeeded,
  2519. // and buf[32] becomes the tweak parameter.
  2520. crypto_wipe(seed, 32);
  2521. COPY(hidden , buf + 32, 32);
  2522. COPY(secret_key, buf , 32);
  2523. WIPE_BUFFER(buf);
  2524. WIPE_BUFFER(pk);
  2525. }
  2526. ///////////////////////
  2527. /// Scalar division ///
  2528. ///////////////////////
  2529. // Montgomery reduction.
  2530. // Divides x by (2^256), and reduces the result modulo L
  2531. //
  2532. // Precondition:
  2533. // x < L * 2^256
  2534. // Constants:
  2535. // r = 2^256 (makes division by r trivial)
  2536. // k = (r * (1/r) - 1) // L (1/r is computed modulo L )
  2537. // Algorithm:
  2538. // s = (x * k) % r
  2539. // t = x + s*L (t is always a multiple of r)
  2540. // u = (t/r) % L (u is always below 2*L, conditional subtraction is enough)
  2541. static void redc(u32 u[8], u32 x[16])
  2542. {
  2543. static const u32 k[8] = {
  2544. 0x12547e1b, 0xd2b51da3, 0xfdba84ff, 0xb1a206f2,
  2545. 0xffa36bea, 0x14e75438, 0x6fe91836, 0x9db6c6f2,
  2546. };
  2547. // s = x * k (modulo 2^256)
  2548. // This is cheaper than the full multiplication.
  2549. u32 s[8] = {0};
  2550. FOR (i, 0, 8) {
  2551. u64 carry = 0;
  2552. FOR (j, 0, 8-i) {
  2553. carry += s[i+j] + (u64)x[i] * k[j];
  2554. s[i+j] = (u32)carry;
  2555. carry >>= 32;
  2556. }
  2557. }
  2558. u32 t[16] = {0};
  2559. multiply(t, s, L);
  2560. // t = t + x
  2561. u64 carry = 0;
  2562. FOR (i, 0, 16) {
  2563. carry += (u64)t[i] + x[i];
  2564. t[i] = (u32)carry;
  2565. carry >>= 32;
  2566. }
  2567. // u = (t / 2^256) % L
  2568. // Note that t / 2^256 is always below 2*L,
  2569. // So a constant time conditional subtraction is enough
  2570. remove_l(u, t+8);
  2571. WIPE_BUFFER(s);
  2572. WIPE_BUFFER(t);
  2573. }
  2574. void crypto_x25519_inverse(u8 blind_salt [32], const u8 private_key[32],
  2575. const u8 curve_point[32])
  2576. {
  2577. static const u8 Lm2[32] = { // L - 2
  2578. 0xeb, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
  2579. 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
  2580. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2581. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
  2582. };
  2583. // 1 in Montgomery form
  2584. u32 m_inv [8] = {
  2585. 0x8d98951d, 0xd6ec3174, 0x737dcf70, 0xc6ef5bf4,
  2586. 0xfffffffe, 0xffffffff, 0xffffffff, 0x0fffffff,
  2587. };
  2588. u8 scalar[32];
  2589. crypto_eddsa_trim_scalar(scalar, private_key);
  2590. // Convert the scalar in Montgomery form
  2591. // m_scl = scalar * 2^256 (modulo L)
  2592. u32 m_scl[8];
  2593. {
  2594. u32 tmp[16];
  2595. ZERO(tmp, 8);
  2596. load32_le_buf(tmp+8, scalar, 8);
  2597. mod_l(scalar, tmp);
  2598. load32_le_buf(m_scl, scalar, 8);
  2599. WIPE_BUFFER(tmp); // Wipe ASAP to save stack space
  2600. }
  2601. // Compute the inverse
  2602. u32 product[16];
  2603. for (int i = 252; i >= 0; i--) {
  2604. ZERO(product, 16);
  2605. multiply(product, m_inv, m_inv);
  2606. redc(m_inv, product);
  2607. if (scalar_bit(Lm2, i)) {
  2608. ZERO(product, 16);
  2609. multiply(product, m_inv, m_scl);
  2610. redc(m_inv, product);
  2611. }
  2612. }
  2613. // Convert the inverse *out* of Montgomery form
  2614. // scalar = m_inv / 2^256 (modulo L)
  2615. COPY(product, m_inv, 8);
  2616. ZERO(product + 8, 8);
  2617. redc(m_inv, product);
  2618. store32_le_buf(scalar, m_inv, 8); // the *inverse* of the scalar
  2619. // Clear the cofactor of scalar:
  2620. // cleared = scalar * (3*L + 1) (modulo 8*L)
  2621. // cleared = scalar + scalar * 3 * L (modulo 8*L)
  2622. // Note that (scalar * 3) is reduced modulo 8, so we only need the
  2623. // first byte.
  2624. add_xl(scalar, scalar[0] * 3);
  2625. // Recall that 8*L < 2^256. However it is also very close to
  2626. // 2^255. If we spanned the ladder over 255 bits, random tests
  2627. // wouldn't catch the off-by-one error.
  2628. scalarmult(blind_salt, scalar, curve_point, 256);
  2629. WIPE_BUFFER(scalar); WIPE_BUFFER(m_scl);
  2630. WIPE_BUFFER(product); WIPE_BUFFER(m_inv);
  2631. }
  2632. ////////////////////////////////
  2633. /// Authenticated encryption ///
  2634. ////////////////////////////////
  2635. static void lock_auth(u8 mac[16], const u8 auth_key[32],
  2636. const u8 *ad , size_t ad_size,
  2637. const u8 *cipher_text, size_t text_size)
  2638. {
  2639. u8 sizes[16]; // Not secret, not wiped
  2640. store64_le(sizes + 0, ad_size);
  2641. store64_le(sizes + 8, text_size);
  2642. crypto_poly1305_ctx poly_ctx; // auto wiped...
  2643. crypto_poly1305_init (&poly_ctx, auth_key);
  2644. crypto_poly1305_update(&poly_ctx, ad , ad_size);
  2645. crypto_poly1305_update(&poly_ctx, zero , gap(ad_size, 16));
  2646. crypto_poly1305_update(&poly_ctx, cipher_text, text_size);
  2647. crypto_poly1305_update(&poly_ctx, zero , gap(text_size, 16));
  2648. crypto_poly1305_update(&poly_ctx, sizes , 16);
  2649. crypto_poly1305_final (&poly_ctx, mac); // ...here
  2650. }
  2651. void crypto_aead_init_x(crypto_aead_ctx *ctx,
  2652. u8 const key[32], const u8 nonce[24])
  2653. {
  2654. crypto_chacha20_h(ctx->key, key, nonce);
  2655. COPY(ctx->nonce, nonce + 16, 8);
  2656. ctx->counter = 0;
  2657. }
  2658. void crypto_aead_init_djb(crypto_aead_ctx *ctx,
  2659. const u8 key[32], const u8 nonce[8])
  2660. {
  2661. COPY(ctx->key , key , 32);
  2662. COPY(ctx->nonce, nonce, 8);
  2663. ctx->counter = 0;
  2664. }
  2665. void crypto_aead_init_ietf(crypto_aead_ctx *ctx,
  2666. const u8 key[32], const u8 nonce[12])
  2667. {
  2668. COPY(ctx->key , key , 32);
  2669. COPY(ctx->nonce, nonce + 4, 8);
  2670. ctx->counter = (u64)load32_le(nonce) << 32;
  2671. }
  2672. void crypto_aead_write(crypto_aead_ctx *ctx, u8 *cipher_text, u8 mac[16],
  2673. const u8 *ad, size_t ad_size,
  2674. const u8 *plain_text, size_t text_size)
  2675. {
  2676. u8 auth_key[64]; // the last 32 bytes are used for rekeying.
  2677. crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter);
  2678. crypto_chacha20_djb(cipher_text, plain_text, text_size,
  2679. ctx->key, ctx->nonce, ctx->counter + 1);
  2680. lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size);
  2681. COPY(ctx->key, auth_key + 32, 32);
  2682. WIPE_BUFFER(auth_key);
  2683. }
  2684. int crypto_aead_read(crypto_aead_ctx *ctx, u8 *plain_text, const u8 mac[16],
  2685. const u8 *ad, size_t ad_size,
  2686. const u8 *cipher_text, size_t text_size)
  2687. {
  2688. u8 auth_key[64]; // the last 32 bytes are used for rekeying.
  2689. u8 real_mac[16];
  2690. crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter);
  2691. lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size);
  2692. int mismatch = crypto_verify16(mac, real_mac);
  2693. if (!mismatch) {
  2694. crypto_chacha20_djb(plain_text, cipher_text, text_size,
  2695. ctx->key, ctx->nonce, ctx->counter + 1);
  2696. COPY(ctx->key, auth_key + 32, 32);
  2697. }
  2698. WIPE_BUFFER(auth_key);
  2699. WIPE_BUFFER(real_mac);
  2700. return mismatch;
  2701. }
  2702. void crypto_aead_lock(u8 *cipher_text, u8 mac[16], const u8 key[32],
  2703. const u8 nonce[24], const u8 *ad, size_t ad_size,
  2704. const u8 *plain_text, size_t text_size)
  2705. {
  2706. crypto_aead_ctx ctx;
  2707. crypto_aead_init_x(&ctx, key, nonce);
  2708. crypto_aead_write(&ctx, cipher_text, mac, ad, ad_size,
  2709. plain_text, text_size);
  2710. crypto_wipe(&ctx, sizeof(ctx));
  2711. }
  2712. int crypto_aead_unlock(u8 *plain_text, const u8 mac[16], const u8 key[32],
  2713. const u8 nonce[24], const u8 *ad, size_t ad_size,
  2714. const u8 *cipher_text, size_t text_size)
  2715. {
  2716. crypto_aead_ctx ctx;
  2717. crypto_aead_init_x(&ctx, key, nonce);
  2718. int mismatch = crypto_aead_read(&ctx, plain_text, mac, ad, ad_size,
  2719. cipher_text, text_size);
  2720. crypto_wipe(&ctx, sizeof(ctx));
  2721. return mismatch;
  2722. }
  2723. #ifdef MONOCYPHER_CPP_NAMESPACE
  2724. }
  2725. #endif