rsa.c 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. /*
  2. * The RSA public-key cryptosystem
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /*
  20. * The following sources were referenced in the design of this implementation
  21. * of the RSA algorithm:
  22. *
  23. * [1] A method for obtaining digital signatures and public-key cryptosystems
  24. * R Rivest, A Shamir, and L Adleman
  25. * http://people.csail.mit.edu/rivest/pubs.html#RSA78
  26. *
  27. * [2] Handbook of Applied Cryptography - 1997, Chapter 8
  28. * Menezes, van Oorschot and Vanstone
  29. *
  30. * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
  31. * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
  32. * Stefan Mangard
  33. * https://arxiv.org/abs/1702.08719v2
  34. *
  35. */
  36. #include "common.h"
  37. #if defined(MBEDTLS_RSA_C)
  38. #include "mbedtls/rsa.h"
  39. #include "mbedtls/rsa_internal.h"
  40. #include "mbedtls/oid.h"
  41. #include "mbedtls/platform_util.h"
  42. #include "mbedtls/error.h"
  43. #include <string.h>
  44. #if defined(MBEDTLS_PKCS1_V21)
  45. #include "mbedtls/md.h"
  46. #endif
  47. #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
  48. #include <stdlib.h>
  49. #endif
  50. #if defined(MBEDTLS_PLATFORM_C)
  51. #include "mbedtls/platform.h"
  52. #else
  53. #include <stdio.h>
  54. #define mbedtls_printf printf
  55. #define mbedtls_calloc calloc
  56. #define mbedtls_free free
  57. #endif
  58. #if !defined(MBEDTLS_RSA_ALT)
  59. /* Parameter validation macros */
  60. #define RSA_VALIDATE_RET( cond ) \
  61. MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
  62. #define RSA_VALIDATE( cond ) \
  63. MBEDTLS_INTERNAL_VALIDATE( cond )
  64. #if defined(MBEDTLS_PKCS1_V15)
  65. /* constant-time buffer comparison */
  66. static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
  67. {
  68. size_t i;
  69. const unsigned char *A = (const unsigned char *) a;
  70. const unsigned char *B = (const unsigned char *) b;
  71. unsigned char diff = 0;
  72. for( i = 0; i < n; i++ )
  73. diff |= A[i] ^ B[i];
  74. return( diff );
  75. }
  76. #endif /* MBEDTLS_PKCS1_V15 */
  77. int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
  78. const mbedtls_mpi *N,
  79. const mbedtls_mpi *P, const mbedtls_mpi *Q,
  80. const mbedtls_mpi *D, const mbedtls_mpi *E )
  81. {
  82. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  83. RSA_VALIDATE_RET( ctx != NULL );
  84. if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) ||
  85. ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ) ||
  86. ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->Q, Q ) ) != 0 ) ||
  87. ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->D, D ) ) != 0 ) ||
  88. ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->E, E ) ) != 0 ) )
  89. {
  90. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  91. }
  92. if( N != NULL )
  93. ctx->len = mbedtls_mpi_size( &ctx->N );
  94. return( 0 );
  95. }
  96. int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,
  97. unsigned char const *N, size_t N_len,
  98. unsigned char const *P, size_t P_len,
  99. unsigned char const *Q, size_t Q_len,
  100. unsigned char const *D, size_t D_len,
  101. unsigned char const *E, size_t E_len )
  102. {
  103. int ret = 0;
  104. RSA_VALIDATE_RET( ctx != NULL );
  105. if( N != NULL )
  106. {
  107. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N, N, N_len ) );
  108. ctx->len = mbedtls_mpi_size( &ctx->N );
  109. }
  110. if( P != NULL )
  111. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P, P, P_len ) );
  112. if( Q != NULL )
  113. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q, Q, Q_len ) );
  114. if( D != NULL )
  115. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D, D, D_len ) );
  116. if( E != NULL )
  117. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E, E, E_len ) );
  118. cleanup:
  119. if( ret != 0 )
  120. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  121. return( 0 );
  122. }
  123. /*
  124. * Checks whether the context fields are set in such a way
  125. * that the RSA primitives will be able to execute without error.
  126. * It does *not* make guarantees for consistency of the parameters.
  127. */
  128. static int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv,
  129. int blinding_needed )
  130. {
  131. #if !defined(MBEDTLS_RSA_NO_CRT)
  132. /* blinding_needed is only used for NO_CRT to decide whether
  133. * P,Q need to be present or not. */
  134. ((void) blinding_needed);
  135. #endif
  136. if( ctx->len != mbedtls_mpi_size( &ctx->N ) ||
  137. ctx->len > MBEDTLS_MPI_MAX_SIZE )
  138. {
  139. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  140. }
  141. /*
  142. * 1. Modular exponentiation needs positive, odd moduli.
  143. */
  144. /* Modular exponentiation wrt. N is always used for
  145. * RSA public key operations. */
  146. if( mbedtls_mpi_cmp_int( &ctx->N, 0 ) <= 0 ||
  147. mbedtls_mpi_get_bit( &ctx->N, 0 ) == 0 )
  148. {
  149. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  150. }
  151. #if !defined(MBEDTLS_RSA_NO_CRT)
  152. /* Modular exponentiation for P and Q is only
  153. * used for private key operations and if CRT
  154. * is used. */
  155. if( is_priv &&
  156. ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||
  157. mbedtls_mpi_get_bit( &ctx->P, 0 ) == 0 ||
  158. mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ||
  159. mbedtls_mpi_get_bit( &ctx->Q, 0 ) == 0 ) )
  160. {
  161. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  162. }
  163. #endif /* !MBEDTLS_RSA_NO_CRT */
  164. /*
  165. * 2. Exponents must be positive
  166. */
  167. /* Always need E for public key operations */
  168. if( mbedtls_mpi_cmp_int( &ctx->E, 0 ) <= 0 )
  169. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  170. #if defined(MBEDTLS_RSA_NO_CRT)
  171. /* For private key operations, use D or DP & DQ
  172. * as (unblinded) exponents. */
  173. if( is_priv && mbedtls_mpi_cmp_int( &ctx->D, 0 ) <= 0 )
  174. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  175. #else
  176. if( is_priv &&
  177. ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) <= 0 ||
  178. mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) <= 0 ) )
  179. {
  180. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  181. }
  182. #endif /* MBEDTLS_RSA_NO_CRT */
  183. /* Blinding shouldn't make exponents negative either,
  184. * so check that P, Q >= 1 if that hasn't yet been
  185. * done as part of 1. */
  186. #if defined(MBEDTLS_RSA_NO_CRT)
  187. if( is_priv && blinding_needed &&
  188. ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||
  189. mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ) )
  190. {
  191. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  192. }
  193. #endif
  194. /* It wouldn't lead to an error if it wasn't satisfied,
  195. * but check for QP >= 1 nonetheless. */
  196. #if !defined(MBEDTLS_RSA_NO_CRT)
  197. if( is_priv &&
  198. mbedtls_mpi_cmp_int( &ctx->QP, 0 ) <= 0 )
  199. {
  200. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  201. }
  202. #endif
  203. return( 0 );
  204. }
  205. int mbedtls_rsa_complete( mbedtls_rsa_context *ctx )
  206. {
  207. int ret = 0;
  208. int have_N, have_P, have_Q, have_D, have_E;
  209. #if !defined(MBEDTLS_RSA_NO_CRT)
  210. int have_DP, have_DQ, have_QP;
  211. #endif
  212. int n_missing, pq_missing, d_missing, is_pub, is_priv;
  213. RSA_VALIDATE_RET( ctx != NULL );
  214. have_N = ( mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 );
  215. have_P = ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 );
  216. have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 );
  217. have_D = ( mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 );
  218. have_E = ( mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0 );
  219. #if !defined(MBEDTLS_RSA_NO_CRT)
  220. have_DP = ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) != 0 );
  221. have_DQ = ( mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) != 0 );
  222. have_QP = ( mbedtls_mpi_cmp_int( &ctx->QP, 0 ) != 0 );
  223. #endif
  224. /*
  225. * Check whether provided parameters are enough
  226. * to deduce all others. The following incomplete
  227. * parameter sets for private keys are supported:
  228. *
  229. * (1) P, Q missing.
  230. * (2) D and potentially N missing.
  231. *
  232. */
  233. n_missing = have_P && have_Q && have_D && have_E;
  234. pq_missing = have_N && !have_P && !have_Q && have_D && have_E;
  235. d_missing = have_P && have_Q && !have_D && have_E;
  236. is_pub = have_N && !have_P && !have_Q && !have_D && have_E;
  237. /* These three alternatives are mutually exclusive */
  238. is_priv = n_missing || pq_missing || d_missing;
  239. if( !is_priv && !is_pub )
  240. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  241. /*
  242. * Step 1: Deduce N if P, Q are provided.
  243. */
  244. if( !have_N && have_P && have_Q )
  245. {
  246. if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P,
  247. &ctx->Q ) ) != 0 )
  248. {
  249. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  250. }
  251. ctx->len = mbedtls_mpi_size( &ctx->N );
  252. }
  253. /*
  254. * Step 2: Deduce and verify all remaining core parameters.
  255. */
  256. if( pq_missing )
  257. {
  258. ret = mbedtls_rsa_deduce_primes( &ctx->N, &ctx->E, &ctx->D,
  259. &ctx->P, &ctx->Q );
  260. if( ret != 0 )
  261. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  262. }
  263. else if( d_missing )
  264. {
  265. if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P,
  266. &ctx->Q,
  267. &ctx->E,
  268. &ctx->D ) ) != 0 )
  269. {
  270. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  271. }
  272. }
  273. /*
  274. * Step 3: Deduce all additional parameters specific
  275. * to our current RSA implementation.
  276. */
  277. #if !defined(MBEDTLS_RSA_NO_CRT)
  278. if( is_priv && ! ( have_DP && have_DQ && have_QP ) )
  279. {
  280. ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,
  281. &ctx->DP, &ctx->DQ, &ctx->QP );
  282. if( ret != 0 )
  283. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  284. }
  285. #endif /* MBEDTLS_RSA_NO_CRT */
  286. /*
  287. * Step 3: Basic sanity checks
  288. */
  289. return( rsa_check_context( ctx, is_priv, 1 ) );
  290. }
  291. int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,
  292. unsigned char *N, size_t N_len,
  293. unsigned char *P, size_t P_len,
  294. unsigned char *Q, size_t Q_len,
  295. unsigned char *D, size_t D_len,
  296. unsigned char *E, size_t E_len )
  297. {
  298. int ret = 0;
  299. int is_priv;
  300. RSA_VALIDATE_RET( ctx != NULL );
  301. /* Check if key is private or public */
  302. is_priv =
  303. mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  304. mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  305. mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  306. mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  307. mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  308. if( !is_priv )
  309. {
  310. /* If we're trying to export private parameters for a public key,
  311. * something must be wrong. */
  312. if( P != NULL || Q != NULL || D != NULL )
  313. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  314. }
  315. if( N != NULL )
  316. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N, N, N_len ) );
  317. if( P != NULL )
  318. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P, P, P_len ) );
  319. if( Q != NULL )
  320. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q, Q, Q_len ) );
  321. if( D != NULL )
  322. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D, D, D_len ) );
  323. if( E != NULL )
  324. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E, E, E_len ) );
  325. cleanup:
  326. return( ret );
  327. }
  328. int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
  329. mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
  330. mbedtls_mpi *D, mbedtls_mpi *E )
  331. {
  332. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  333. int is_priv;
  334. RSA_VALIDATE_RET( ctx != NULL );
  335. /* Check if key is private or public */
  336. is_priv =
  337. mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  338. mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  339. mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  340. mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  341. mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  342. if( !is_priv )
  343. {
  344. /* If we're trying to export private parameters for a public key,
  345. * something must be wrong. */
  346. if( P != NULL || Q != NULL || D != NULL )
  347. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  348. }
  349. /* Export all requested core parameters. */
  350. if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N ) ) != 0 ) ||
  351. ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P ) ) != 0 ) ||
  352. ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q ) ) != 0 ) ||
  353. ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D ) ) != 0 ) ||
  354. ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E ) ) != 0 ) )
  355. {
  356. return( ret );
  357. }
  358. return( 0 );
  359. }
  360. /*
  361. * Export CRT parameters
  362. * This must also be implemented if CRT is not used, for being able to
  363. * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
  364. * can be used in this case.
  365. */
  366. int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
  367. mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )
  368. {
  369. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  370. int is_priv;
  371. RSA_VALIDATE_RET( ctx != NULL );
  372. /* Check if key is private or public */
  373. is_priv =
  374. mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  375. mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  376. mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  377. mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  378. mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  379. if( !is_priv )
  380. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  381. #if !defined(MBEDTLS_RSA_NO_CRT)
  382. /* Export all requested blinding parameters. */
  383. if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP ) ) != 0 ) ||
  384. ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ ) ) != 0 ) ||
  385. ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP ) ) != 0 ) )
  386. {
  387. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  388. }
  389. #else
  390. if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,
  391. DP, DQ, QP ) ) != 0 )
  392. {
  393. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret ) );
  394. }
  395. #endif
  396. return( 0 );
  397. }
  398. /*
  399. * Initialize an RSA context
  400. */
  401. void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
  402. int padding,
  403. int hash_id )
  404. {
  405. RSA_VALIDATE( ctx != NULL );
  406. RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 ||
  407. padding == MBEDTLS_RSA_PKCS_V21 );
  408. memset( ctx, 0, sizeof( mbedtls_rsa_context ) );
  409. mbedtls_rsa_set_padding( ctx, padding, hash_id );
  410. #if defined(MBEDTLS_THREADING_C)
  411. /* Set ctx->ver to nonzero to indicate that the mutex has been
  412. * initialized and will need to be freed. */
  413. ctx->ver = 1;
  414. mbedtls_mutex_init( &ctx->mutex );
  415. #endif
  416. }
  417. /*
  418. * Set padding for an existing RSA context
  419. */
  420. void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding,
  421. int hash_id )
  422. {
  423. RSA_VALIDATE( ctx != NULL );
  424. RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 ||
  425. padding == MBEDTLS_RSA_PKCS_V21 );
  426. ctx->padding = padding;
  427. ctx->hash_id = hash_id;
  428. }
  429. /*
  430. * Get length in bytes of RSA modulus
  431. */
  432. size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )
  433. {
  434. return( ctx->len );
  435. }
  436. #if defined(MBEDTLS_GENPRIME)
  437. /*
  438. * Generate an RSA keypair
  439. *
  440. * This generation method follows the RSA key pair generation procedure of
  441. * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
  442. */
  443. int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
  444. int (*f_rng)(void *, unsigned char *, size_t),
  445. void *p_rng,
  446. unsigned int nbits, int exponent )
  447. {
  448. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  449. mbedtls_mpi H, G, L;
  450. int prime_quality = 0;
  451. RSA_VALIDATE_RET( ctx != NULL );
  452. RSA_VALIDATE_RET( f_rng != NULL );
  453. /*
  454. * If the modulus is 1024 bit long or shorter, then the security strength of
  455. * the RSA algorithm is less than or equal to 80 bits and therefore an error
  456. * rate of 2^-80 is sufficient.
  457. */
  458. if( nbits > 1024 )
  459. prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
  460. mbedtls_mpi_init( &H );
  461. mbedtls_mpi_init( &G );
  462. mbedtls_mpi_init( &L );
  463. if( nbits < 128 || exponent < 3 || nbits % 2 != 0 )
  464. {
  465. ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  466. goto cleanup;
  467. }
  468. /*
  469. * find primes P and Q with Q < P so that:
  470. * 1. |P-Q| > 2^( nbits / 2 - 100 )
  471. * 2. GCD( E, (P-1)*(Q-1) ) == 1
  472. * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
  473. */
  474. MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) );
  475. do
  476. {
  477. MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1,
  478. prime_quality, f_rng, p_rng ) );
  479. MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1,
  480. prime_quality, f_rng, p_rng ) );
  481. /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
  482. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) );
  483. if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) )
  484. continue;
  485. /* not required by any standards, but some users rely on the fact that P > Q */
  486. if( H.s < 0 )
  487. mbedtls_mpi_swap( &ctx->P, &ctx->Q );
  488. /* Temporarily replace P,Q by P-1, Q-1 */
  489. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) );
  490. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) );
  491. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) );
  492. /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
  493. MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H ) );
  494. if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
  495. continue;
  496. /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
  497. MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) );
  498. MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) );
  499. MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) );
  500. if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a))
  501. continue;
  502. break;
  503. }
  504. while( 1 );
  505. /* Restore P,Q */
  506. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P, &ctx->P, 1 ) );
  507. MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q, &ctx->Q, 1 ) );
  508. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );
  509. ctx->len = mbedtls_mpi_size( &ctx->N );
  510. #if !defined(MBEDTLS_RSA_NO_CRT)
  511. /*
  512. * DP = D mod (P - 1)
  513. * DQ = D mod (Q - 1)
  514. * QP = Q^-1 mod P
  515. */
  516. MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,
  517. &ctx->DP, &ctx->DQ, &ctx->QP ) );
  518. #endif /* MBEDTLS_RSA_NO_CRT */
  519. /* Double-check */
  520. MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) );
  521. cleanup:
  522. mbedtls_mpi_free( &H );
  523. mbedtls_mpi_free( &G );
  524. mbedtls_mpi_free( &L );
  525. if( ret != 0 )
  526. {
  527. mbedtls_rsa_free( ctx );
  528. if( ( -ret & ~0x7f ) == 0 )
  529. ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret );
  530. return( ret );
  531. }
  532. return( 0 );
  533. }
  534. #endif /* MBEDTLS_GENPRIME */
  535. /*
  536. * Check a public RSA key
  537. */
  538. int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )
  539. {
  540. RSA_VALIDATE_RET( ctx != NULL );
  541. if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 )
  542. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  543. if( mbedtls_mpi_bitlen( &ctx->N ) < 128 )
  544. {
  545. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  546. }
  547. if( mbedtls_mpi_get_bit( &ctx->E, 0 ) == 0 ||
  548. mbedtls_mpi_bitlen( &ctx->E ) < 2 ||
  549. mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 )
  550. {
  551. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  552. }
  553. return( 0 );
  554. }
  555. /*
  556. * Check for the consistency of all fields in an RSA private key context
  557. */
  558. int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )
  559. {
  560. RSA_VALIDATE_RET( ctx != NULL );
  561. if( mbedtls_rsa_check_pubkey( ctx ) != 0 ||
  562. rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 )
  563. {
  564. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  565. }
  566. if( mbedtls_rsa_validate_params( &ctx->N, &ctx->P, &ctx->Q,
  567. &ctx->D, &ctx->E, NULL, NULL ) != 0 )
  568. {
  569. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  570. }
  571. #if !defined(MBEDTLS_RSA_NO_CRT)
  572. else if( mbedtls_rsa_validate_crt( &ctx->P, &ctx->Q, &ctx->D,
  573. &ctx->DP, &ctx->DQ, &ctx->QP ) != 0 )
  574. {
  575. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  576. }
  577. #endif
  578. return( 0 );
  579. }
  580. /*
  581. * Check if contexts holding a public and private key match
  582. */
  583. int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,
  584. const mbedtls_rsa_context *prv )
  585. {
  586. RSA_VALIDATE_RET( pub != NULL );
  587. RSA_VALIDATE_RET( prv != NULL );
  588. if( mbedtls_rsa_check_pubkey( pub ) != 0 ||
  589. mbedtls_rsa_check_privkey( prv ) != 0 )
  590. {
  591. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  592. }
  593. if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 ||
  594. mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 )
  595. {
  596. return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  597. }
  598. return( 0 );
  599. }
  600. /* NXP added for HW accelerators support */
  601. #if !defined(MBEDTLS_RSA_PUBLIC_ALT)
  602. /*
  603. * Do an RSA public key operation
  604. */
  605. int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
  606. const unsigned char *input,
  607. unsigned char *output )
  608. {
  609. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  610. size_t olen;
  611. mbedtls_mpi T;
  612. RSA_VALIDATE_RET( ctx != NULL );
  613. RSA_VALIDATE_RET( input != NULL );
  614. RSA_VALIDATE_RET( output != NULL );
  615. if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) )
  616. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  617. mbedtls_mpi_init( &T );
  618. #if defined(MBEDTLS_THREADING_C)
  619. if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
  620. return( ret );
  621. #endif
  622. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
  623. if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
  624. {
  625. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  626. goto cleanup;
  627. }
  628. olen = ctx->len;
  629. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) );
  630. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
  631. cleanup:
  632. #if defined(MBEDTLS_THREADING_C)
  633. if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
  634. return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
  635. #endif
  636. mbedtls_mpi_free( &T );
  637. if( ret != 0 )
  638. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret ) );
  639. return( 0 );
  640. }
  641. #endif /* MBEDTLS_RSA_PUBLIC_ALT */
  642. /* NXP added for HW accelerators support */
  643. /*
  644. * Generate or update blinding values, see section 10 of:
  645. * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
  646. * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
  647. * Berlin Heidelberg, 1996. p. 104-113.
  648. */
  649. static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
  650. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
  651. {
  652. int ret, count = 0;
  653. mbedtls_mpi R;
  654. mbedtls_mpi_init( &R );
  655. if( ctx->Vf.p != NULL )
  656. {
  657. /* We already have blinding values, just update them by squaring */
  658. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );
  659. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
  660. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );
  661. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) );
  662. goto cleanup;
  663. }
  664. /* Unblinding value: Vf = random number, invertible mod N */
  665. do {
  666. if( count++ > 10 )
  667. {
  668. ret = MBEDTLS_ERR_RSA_RNG_FAILED;
  669. goto cleanup;
  670. }
  671. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) );
  672. /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
  673. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, ctx->len - 1, f_rng, p_rng ) );
  674. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vf, &R ) );
  675. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
  676. /* At this point, Vi is invertible mod N if and only if both Vf and R
  677. * are invertible mod N. If one of them isn't, we don't need to know
  678. * which one, we just loop and choose new values for both of them.
  679. * (Each iteration succeeds with overwhelming probability.) */
  680. ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vi, &ctx->N );
  681. if( ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
  682. goto cleanup;
  683. } while( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
  684. /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
  685. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &R ) );
  686. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
  687. /* Blinding value: Vi = Vf^(-e) mod N
  688. * (Vi already contains Vf^-1 at this point) */
  689. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );
  690. cleanup:
  691. mbedtls_mpi_free( &R );
  692. return( ret );
  693. }
  694. /*
  695. * Exponent blinding supposed to prevent side-channel attacks using multiple
  696. * traces of measurements to recover the RSA key. The more collisions are there,
  697. * the more bits of the key can be recovered. See [3].
  698. *
  699. * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
  700. * observations on avarage.
  701. *
  702. * For example with 28 byte blinding to achieve 2 collisions the adversary has
  703. * to make 2^112 observations on avarage.
  704. *
  705. * (With the currently (as of 2017 April) known best algorithms breaking 2048
  706. * bit RSA requires approximately as much time as trying out 2^112 random keys.
  707. * Thus in this sense with 28 byte blinding the security is not reduced by
  708. * side-channel attacks like the one in [3])
  709. *
  710. * This countermeasure does not help if the key recovery is possible with a
  711. * single trace.
  712. */
  713. #define RSA_EXPONENT_BLINDING 28
  714. /*
  715. * Do an RSA private key operation
  716. */
  717. int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
  718. int (*f_rng)(void *, unsigned char *, size_t),
  719. void *p_rng,
  720. const unsigned char *input,
  721. unsigned char *output )
  722. {
  723. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  724. size_t olen;
  725. /* Temporary holding the result */
  726. mbedtls_mpi T;
  727. /* Temporaries holding P-1, Q-1 and the
  728. * exponent blinding factor, respectively. */
  729. mbedtls_mpi P1, Q1, R;
  730. #if !defined(MBEDTLS_RSA_NO_CRT)
  731. /* Temporaries holding the results mod p resp. mod q. */
  732. mbedtls_mpi TP, TQ;
  733. /* Temporaries holding the blinded exponents for
  734. * the mod p resp. mod q computation (if used). */
  735. mbedtls_mpi DP_blind, DQ_blind;
  736. /* Pointers to actual exponents to be used - either the unblinded
  737. * or the blinded ones, depending on the presence of a PRNG. */
  738. mbedtls_mpi *DP = &ctx->DP;
  739. mbedtls_mpi *DQ = &ctx->DQ;
  740. #else
  741. /* Temporary holding the blinded exponent (if used). */
  742. mbedtls_mpi D_blind;
  743. /* Pointer to actual exponent to be used - either the unblinded
  744. * or the blinded one, depending on the presence of a PRNG. */
  745. mbedtls_mpi *D = &ctx->D;
  746. #endif /* MBEDTLS_RSA_NO_CRT */
  747. /* Temporaries holding the initial input and the double
  748. * checked result; should be the same in the end. */
  749. mbedtls_mpi I, C;
  750. RSA_VALIDATE_RET( ctx != NULL );
  751. RSA_VALIDATE_RET( input != NULL );
  752. RSA_VALIDATE_RET( output != NULL );
  753. if( rsa_check_context( ctx, 1 /* private key checks */,
  754. f_rng != NULL /* blinding y/n */ ) != 0 )
  755. {
  756. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  757. }
  758. #if defined(MBEDTLS_THREADING_C)
  759. if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
  760. return( ret );
  761. #endif
  762. /* MPI Initialization */
  763. mbedtls_mpi_init( &T );
  764. mbedtls_mpi_init( &P1 );
  765. mbedtls_mpi_init( &Q1 );
  766. mbedtls_mpi_init( &R );
  767. if( f_rng != NULL )
  768. {
  769. #if defined(MBEDTLS_RSA_NO_CRT)
  770. mbedtls_mpi_init( &D_blind );
  771. #else
  772. mbedtls_mpi_init( &DP_blind );
  773. mbedtls_mpi_init( &DQ_blind );
  774. #endif
  775. }
  776. #if !defined(MBEDTLS_RSA_NO_CRT)
  777. mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ );
  778. #endif
  779. mbedtls_mpi_init( &I );
  780. mbedtls_mpi_init( &C );
  781. /* End of MPI initialization */
  782. MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
  783. if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
  784. {
  785. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  786. goto cleanup;
  787. }
  788. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) );
  789. if( f_rng != NULL )
  790. {
  791. /*
  792. * Blinding
  793. * T = T * Vi mod N
  794. */
  795. MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) );
  796. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) );
  797. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
  798. /*
  799. * Exponent blinding
  800. */
  801. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
  802. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
  803. #if defined(MBEDTLS_RSA_NO_CRT)
  804. /*
  805. * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
  806. */
  807. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  808. f_rng, p_rng ) );
  809. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) );
  810. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) );
  811. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) );
  812. D = &D_blind;
  813. #else
  814. /*
  815. * DP_blind = ( P - 1 ) * R + DP
  816. */
  817. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  818. f_rng, p_rng ) );
  819. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );
  820. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,
  821. &ctx->DP ) );
  822. DP = &DP_blind;
  823. /*
  824. * DQ_blind = ( Q - 1 ) * R + DQ
  825. */
  826. MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  827. f_rng, p_rng ) );
  828. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) );
  829. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind,
  830. &ctx->DQ ) );
  831. DQ = &DQ_blind;
  832. #endif /* MBEDTLS_RSA_NO_CRT */
  833. }
  834. #if defined(MBEDTLS_RSA_NO_CRT)
  835. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) );
  836. #else
  837. /*
  838. * Faster decryption using the CRT
  839. *
  840. * TP = input ^ dP mod P
  841. * TQ = input ^ dQ mod Q
  842. */
  843. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) );
  844. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) );
  845. /*
  846. * T = (TP - TQ) * (Q^-1 mod P) mod P
  847. */
  848. MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) );
  849. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) );
  850. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) );
  851. /*
  852. * T = TQ + T * Q
  853. */
  854. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) );
  855. MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) );
  856. #endif /* MBEDTLS_RSA_NO_CRT */
  857. if( f_rng != NULL )
  858. {
  859. /*
  860. * Unblind
  861. * T = T * Vf mod N
  862. */
  863. MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) );
  864. MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
  865. }
  866. /* Verify the result to prevent glitching attacks. */
  867. MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E,
  868. &ctx->N, &ctx->RN ) );
  869. if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 )
  870. {
  871. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  872. goto cleanup;
  873. }
  874. olen = ctx->len;
  875. MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
  876. cleanup:
  877. #if defined(MBEDTLS_THREADING_C)
  878. if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
  879. return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
  880. #endif
  881. mbedtls_mpi_free( &P1 );
  882. mbedtls_mpi_free( &Q1 );
  883. mbedtls_mpi_free( &R );
  884. if( f_rng != NULL )
  885. {
  886. #if defined(MBEDTLS_RSA_NO_CRT)
  887. mbedtls_mpi_free( &D_blind );
  888. #else
  889. mbedtls_mpi_free( &DP_blind );
  890. mbedtls_mpi_free( &DQ_blind );
  891. #endif
  892. }
  893. mbedtls_mpi_free( &T );
  894. #if !defined(MBEDTLS_RSA_NO_CRT)
  895. mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ );
  896. #endif
  897. mbedtls_mpi_free( &C );
  898. mbedtls_mpi_free( &I );
  899. if( ret != 0 && ret >= -0x007f )
  900. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret ) );
  901. return( ret );
  902. }
  903. #if defined(MBEDTLS_PKCS1_V21)
  904. /**
  905. * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
  906. *
  907. * \param dst buffer to mask
  908. * \param dlen length of destination buffer
  909. * \param src source of the mask generation
  910. * \param slen length of the source buffer
  911. * \param md_ctx message digest context to use
  912. */
  913. static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
  914. size_t slen, mbedtls_md_context_t *md_ctx )
  915. {
  916. unsigned char mask[MBEDTLS_MD_MAX_SIZE];
  917. unsigned char counter[4];
  918. unsigned char *p;
  919. unsigned int hlen;
  920. size_t i, use_len;
  921. int ret = 0;
  922. memset( mask, 0, MBEDTLS_MD_MAX_SIZE );
  923. memset( counter, 0, 4 );
  924. hlen = mbedtls_md_get_size( md_ctx->md_info );
  925. /* Generate and apply dbMask */
  926. p = dst;
  927. while( dlen > 0 )
  928. {
  929. use_len = hlen;
  930. if( dlen < hlen )
  931. use_len = dlen;
  932. if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 )
  933. goto exit;
  934. if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 )
  935. goto exit;
  936. if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 )
  937. goto exit;
  938. if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 )
  939. goto exit;
  940. for( i = 0; i < use_len; ++i )
  941. *p++ ^= mask[i];
  942. counter[3]++;
  943. dlen -= use_len;
  944. }
  945. exit:
  946. mbedtls_platform_zeroize( mask, sizeof( mask ) );
  947. return( ret );
  948. }
  949. #endif /* MBEDTLS_PKCS1_V21 */
  950. #if defined(MBEDTLS_PKCS1_V21)
  951. /*
  952. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
  953. */
  954. int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
  955. int (*f_rng)(void *, unsigned char *, size_t),
  956. void *p_rng,
  957. int mode,
  958. const unsigned char *label, size_t label_len,
  959. size_t ilen,
  960. const unsigned char *input,
  961. unsigned char *output )
  962. {
  963. size_t olen;
  964. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  965. unsigned char *p = output;
  966. unsigned int hlen;
  967. const mbedtls_md_info_t *md_info;
  968. mbedtls_md_context_t md_ctx;
  969. RSA_VALIDATE_RET( ctx != NULL );
  970. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  971. mode == MBEDTLS_RSA_PUBLIC );
  972. RSA_VALIDATE_RET( output != NULL );
  973. RSA_VALIDATE_RET( ilen == 0 || input != NULL );
  974. RSA_VALIDATE_RET( label_len == 0 || label != NULL );
  975. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  976. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  977. if( f_rng == NULL )
  978. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  979. md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  980. if( md_info == NULL )
  981. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  982. olen = ctx->len;
  983. hlen = mbedtls_md_get_size( md_info );
  984. /* first comparison checks for overflow */
  985. if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
  986. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  987. memset( output, 0, olen );
  988. *p++ = 0;
  989. /* Generate a random octet string seed */
  990. if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
  991. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_RNG_FAILED, ret ) );
  992. p += hlen;
  993. /* Construct DB */
  994. if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 )
  995. return( ret );
  996. p += hlen;
  997. p += olen - 2 * hlen - 2 - ilen;
  998. *p++ = 1;
  999. if( ilen != 0 )
  1000. memcpy( p, input, ilen );
  1001. mbedtls_md_init( &md_ctx );
  1002. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1003. goto exit;
  1004. /* maskedDB: Apply dbMask to DB */
  1005. if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
  1006. &md_ctx ) ) != 0 )
  1007. goto exit;
  1008. /* maskedSeed: Apply seedMask to seed */
  1009. if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
  1010. &md_ctx ) ) != 0 )
  1011. goto exit;
  1012. exit:
  1013. mbedtls_md_free( &md_ctx );
  1014. if( ret != 0 )
  1015. return( ret );
  1016. return( ( mode == MBEDTLS_RSA_PUBLIC )
  1017. ? mbedtls_rsa_public( ctx, output, output )
  1018. : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
  1019. }
  1020. #endif /* MBEDTLS_PKCS1_V21 */
  1021. #if defined(MBEDTLS_PKCS1_V15)
  1022. /*
  1023. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
  1024. */
  1025. int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
  1026. int (*f_rng)(void *, unsigned char *, size_t),
  1027. void *p_rng,
  1028. int mode, size_t ilen,
  1029. const unsigned char *input,
  1030. unsigned char *output )
  1031. {
  1032. size_t nb_pad, olen;
  1033. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1034. unsigned char *p = output;
  1035. RSA_VALIDATE_RET( ctx != NULL );
  1036. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1037. mode == MBEDTLS_RSA_PUBLIC );
  1038. RSA_VALIDATE_RET( output != NULL );
  1039. RSA_VALIDATE_RET( ilen == 0 || input != NULL );
  1040. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  1041. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1042. olen = ctx->len;
  1043. /* first comparison checks for overflow */
  1044. if( ilen + 11 < ilen || olen < ilen + 11 )
  1045. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1046. nb_pad = olen - 3 - ilen;
  1047. *p++ = 0;
  1048. if( mode == MBEDTLS_RSA_PUBLIC )
  1049. {
  1050. if( f_rng == NULL )
  1051. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1052. *p++ = MBEDTLS_RSA_CRYPT;
  1053. while( nb_pad-- > 0 )
  1054. {
  1055. int rng_dl = 100;
  1056. do {
  1057. ret = f_rng( p_rng, p, 1 );
  1058. } while( *p == 0 && --rng_dl && ret == 0 );
  1059. /* Check if RNG failed to generate data */
  1060. if( rng_dl == 0 || ret != 0 )
  1061. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_RNG_FAILED, ret ) );
  1062. p++;
  1063. }
  1064. }
  1065. else
  1066. {
  1067. *p++ = MBEDTLS_RSA_SIGN;
  1068. while( nb_pad-- > 0 )
  1069. *p++ = 0xFF;
  1070. }
  1071. *p++ = 0;
  1072. if( ilen != 0 )
  1073. memcpy( p, input, ilen );
  1074. return( ( mode == MBEDTLS_RSA_PUBLIC )
  1075. ? mbedtls_rsa_public( ctx, output, output )
  1076. : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
  1077. }
  1078. #endif /* MBEDTLS_PKCS1_V15 */
  1079. /*
  1080. * Add the message padding, then do an RSA operation
  1081. */
  1082. int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
  1083. int (*f_rng)(void *, unsigned char *, size_t),
  1084. void *p_rng,
  1085. int mode, size_t ilen,
  1086. const unsigned char *input,
  1087. unsigned char *output )
  1088. {
  1089. RSA_VALIDATE_RET( ctx != NULL );
  1090. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1091. mode == MBEDTLS_RSA_PUBLIC );
  1092. RSA_VALIDATE_RET( output != NULL );
  1093. RSA_VALIDATE_RET( ilen == 0 || input != NULL );
  1094. switch( ctx->padding )
  1095. {
  1096. #if defined(MBEDTLS_PKCS1_V15)
  1097. case MBEDTLS_RSA_PKCS_V15:
  1098. return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,
  1099. input, output );
  1100. #endif
  1101. #if defined(MBEDTLS_PKCS1_V21)
  1102. case MBEDTLS_RSA_PKCS_V21:
  1103. return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,
  1104. ilen, input, output );
  1105. #endif
  1106. default:
  1107. return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1108. }
  1109. }
  1110. #if defined(MBEDTLS_PKCS1_V21)
  1111. /*
  1112. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
  1113. */
  1114. int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
  1115. int (*f_rng)(void *, unsigned char *, size_t),
  1116. void *p_rng,
  1117. int mode,
  1118. const unsigned char *label, size_t label_len,
  1119. size_t *olen,
  1120. const unsigned char *input,
  1121. unsigned char *output,
  1122. size_t output_max_len )
  1123. {
  1124. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1125. size_t ilen, i, pad_len;
  1126. unsigned char *p, bad, pad_done;
  1127. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1128. unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
  1129. unsigned int hlen;
  1130. const mbedtls_md_info_t *md_info;
  1131. mbedtls_md_context_t md_ctx;
  1132. RSA_VALIDATE_RET( ctx != NULL );
  1133. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1134. mode == MBEDTLS_RSA_PUBLIC );
  1135. RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1136. RSA_VALIDATE_RET( label_len == 0 || label != NULL );
  1137. RSA_VALIDATE_RET( input != NULL );
  1138. RSA_VALIDATE_RET( olen != NULL );
  1139. /*
  1140. * Parameters sanity checks
  1141. */
  1142. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1143. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1144. ilen = ctx->len;
  1145. if( ilen < 16 || ilen > sizeof( buf ) )
  1146. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1147. md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  1148. if( md_info == NULL )
  1149. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1150. hlen = mbedtls_md_get_size( md_info );
  1151. // checking for integer underflow
  1152. if( 2 * hlen + 2 > ilen )
  1153. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1154. /*
  1155. * RSA operation
  1156. */
  1157. ret = ( mode == MBEDTLS_RSA_PUBLIC )
  1158. ? mbedtls_rsa_public( ctx, input, buf )
  1159. : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
  1160. if( ret != 0 )
  1161. goto cleanup;
  1162. /*
  1163. * Unmask data and generate lHash
  1164. */
  1165. mbedtls_md_init( &md_ctx );
  1166. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1167. {
  1168. mbedtls_md_free( &md_ctx );
  1169. goto cleanup;
  1170. }
  1171. /* seed: Apply seedMask to maskedSeed */
  1172. if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
  1173. &md_ctx ) ) != 0 ||
  1174. /* DB: Apply dbMask to maskedDB */
  1175. ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
  1176. &md_ctx ) ) != 0 )
  1177. {
  1178. mbedtls_md_free( &md_ctx );
  1179. goto cleanup;
  1180. }
  1181. mbedtls_md_free( &md_ctx );
  1182. /* Generate lHash */
  1183. if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 )
  1184. goto cleanup;
  1185. /*
  1186. * Check contents, in "constant-time"
  1187. */
  1188. p = buf;
  1189. bad = 0;
  1190. bad |= *p++; /* First byte must be 0 */
  1191. p += hlen; /* Skip seed */
  1192. /* Check lHash */
  1193. for( i = 0; i < hlen; i++ )
  1194. bad |= lhash[i] ^ *p++;
  1195. /* Get zero-padding len, but always read till end of buffer
  1196. * (minus one, for the 01 byte) */
  1197. pad_len = 0;
  1198. pad_done = 0;
  1199. for( i = 0; i < ilen - 2 * hlen - 2; i++ )
  1200. {
  1201. pad_done |= p[i];
  1202. pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  1203. }
  1204. p += pad_len;
  1205. bad |= *p++ ^ 0x01;
  1206. /*
  1207. * The only information "leaked" is whether the padding was correct or not
  1208. * (eg, no data is copied if it was not correct). This meets the
  1209. * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
  1210. * the different error conditions.
  1211. */
  1212. if( bad != 0 )
  1213. {
  1214. ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1215. goto cleanup;
  1216. }
  1217. if( ilen - ( p - buf ) > output_max_len )
  1218. {
  1219. ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
  1220. goto cleanup;
  1221. }
  1222. *olen = ilen - (p - buf);
  1223. if( *olen != 0 )
  1224. memcpy( output, p, *olen );
  1225. ret = 0;
  1226. cleanup:
  1227. mbedtls_platform_zeroize( buf, sizeof( buf ) );
  1228. mbedtls_platform_zeroize( lhash, sizeof( lhash ) );
  1229. return( ret );
  1230. }
  1231. #endif /* MBEDTLS_PKCS1_V21 */
  1232. #if defined(MBEDTLS_PKCS1_V15)
  1233. /** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
  1234. *
  1235. * \param value The value to analyze.
  1236. * \return Zero if \p value is zero, otherwise all-bits-one.
  1237. */
  1238. static unsigned all_or_nothing_int( unsigned value )
  1239. {
  1240. /* MSVC has a warning about unary minus on unsigned, but this is
  1241. * well-defined and precisely what we want to do here */
  1242. #if defined(_MSC_VER)
  1243. #pragma warning( push )
  1244. #pragma warning( disable : 4146 )
  1245. #endif
  1246. return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
  1247. #if defined(_MSC_VER)
  1248. #pragma warning( pop )
  1249. #endif
  1250. }
  1251. /** Check whether a size is out of bounds, without branches.
  1252. *
  1253. * This is equivalent to `size > max`, but is likely to be compiled to
  1254. * to code using bitwise operation rather than a branch.
  1255. *
  1256. * \param size Size to check.
  1257. * \param max Maximum desired value for \p size.
  1258. * \return \c 0 if `size <= max`.
  1259. * \return \c 1 if `size > max`.
  1260. */
  1261. static unsigned size_greater_than( size_t size, size_t max )
  1262. {
  1263. /* Return the sign bit (1 for negative) of (max - size). */
  1264. return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) );
  1265. }
  1266. /** Choose between two integer values, without branches.
  1267. *
  1268. * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled
  1269. * to code using bitwise operation rather than a branch.
  1270. *
  1271. * \param cond Condition to test.
  1272. * \param if1 Value to use if \p cond is nonzero.
  1273. * \param if0 Value to use if \p cond is zero.
  1274. * \return \c if1 if \p cond is nonzero, otherwise \c if0.
  1275. */
  1276. static unsigned if_int( unsigned cond, unsigned if1, unsigned if0 )
  1277. {
  1278. unsigned mask = all_or_nothing_int( cond );
  1279. return( ( mask & if1 ) | (~mask & if0 ) );
  1280. }
  1281. /** Shift some data towards the left inside a buffer without leaking
  1282. * the length of the data through side channels.
  1283. *
  1284. * `mem_move_to_left(start, total, offset)` is functionally equivalent to
  1285. * ```
  1286. * memmove(start, start + offset, total - offset);
  1287. * memset(start + offset, 0, total - offset);
  1288. * ```
  1289. * but it strives to use a memory access pattern (and thus total timing)
  1290. * that does not depend on \p offset. This timing independence comes at
  1291. * the expense of performance.
  1292. *
  1293. * \param start Pointer to the start of the buffer.
  1294. * \param total Total size of the buffer.
  1295. * \param offset Offset from which to copy \p total - \p offset bytes.
  1296. */
  1297. static void mem_move_to_left( void *start,
  1298. size_t total,
  1299. size_t offset )
  1300. {
  1301. volatile unsigned char *buf = start;
  1302. size_t i, n;
  1303. if( total == 0 )
  1304. return;
  1305. for( i = 0; i < total; i++ )
  1306. {
  1307. unsigned no_op = size_greater_than( total - offset, i );
  1308. /* The first `total - offset` passes are a no-op. The last
  1309. * `offset` passes shift the data one byte to the left and
  1310. * zero out the last byte. */
  1311. for( n = 0; n < total - 1; n++ )
  1312. {
  1313. unsigned char current = buf[n];
  1314. unsigned char next = buf[n+1];
  1315. buf[n] = if_int( no_op, current, next );
  1316. }
  1317. buf[total-1] = if_int( no_op, buf[total-1], 0 );
  1318. }
  1319. }
  1320. /*
  1321. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
  1322. */
  1323. int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
  1324. int (*f_rng)(void *, unsigned char *, size_t),
  1325. void *p_rng,
  1326. int mode, size_t *olen,
  1327. const unsigned char *input,
  1328. unsigned char *output,
  1329. size_t output_max_len )
  1330. {
  1331. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1332. size_t ilen, i, plaintext_max_size;
  1333. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1334. /* The following variables take sensitive values: their value must
  1335. * not leak into the observable behavior of the function other than
  1336. * the designated outputs (output, olen, return value). Otherwise
  1337. * this would open the execution of the function to
  1338. * side-channel-based variants of the Bleichenbacher padding oracle
  1339. * attack. Potential side channels include overall timing, memory
  1340. * access patterns (especially visible to an adversary who has access
  1341. * to a shared memory cache), and branches (especially visible to
  1342. * an adversary who has access to a shared code cache or to a shared
  1343. * branch predictor). */
  1344. size_t pad_count = 0;
  1345. unsigned bad = 0;
  1346. unsigned char pad_done = 0;
  1347. size_t plaintext_size = 0;
  1348. unsigned output_too_large;
  1349. RSA_VALIDATE_RET( ctx != NULL );
  1350. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1351. mode == MBEDTLS_RSA_PUBLIC );
  1352. RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1353. RSA_VALIDATE_RET( input != NULL );
  1354. RSA_VALIDATE_RET( olen != NULL );
  1355. ilen = ctx->len;
  1356. plaintext_max_size = ( output_max_len > ilen - 11 ?
  1357. ilen - 11 :
  1358. output_max_len );
  1359. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  1360. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1361. if( ilen < 16 || ilen > sizeof( buf ) )
  1362. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1363. ret = ( mode == MBEDTLS_RSA_PUBLIC )
  1364. ? mbedtls_rsa_public( ctx, input, buf )
  1365. : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
  1366. if( ret != 0 )
  1367. goto cleanup;
  1368. /* Check and get padding length in constant time and constant
  1369. * memory trace. The first byte must be 0. */
  1370. bad |= buf[0];
  1371. if( mode == MBEDTLS_RSA_PRIVATE )
  1372. {
  1373. /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  1374. * where PS must be at least 8 nonzero bytes. */
  1375. bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
  1376. /* Read the whole buffer. Set pad_done to nonzero if we find
  1377. * the 0x00 byte and remember the padding length in pad_count. */
  1378. for( i = 2; i < ilen; i++ )
  1379. {
  1380. pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
  1381. pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  1382. }
  1383. }
  1384. else
  1385. {
  1386. /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
  1387. * where PS must be at least 8 bytes with the value 0xFF. */
  1388. bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
  1389. /* Read the whole buffer. Set pad_done to nonzero if we find
  1390. * the 0x00 byte and remember the padding length in pad_count.
  1391. * If there's a non-0xff byte in the padding, the padding is bad. */
  1392. for( i = 2; i < ilen; i++ )
  1393. {
  1394. pad_done |= if_int( buf[i], 0, 1 );
  1395. pad_count += if_int( pad_done, 0, 1 );
  1396. bad |= if_int( pad_done, 0, buf[i] ^ 0xFF );
  1397. }
  1398. }
  1399. /* If pad_done is still zero, there's no data, only unfinished padding. */
  1400. bad |= if_int( pad_done, 0, 1 );
  1401. /* There must be at least 8 bytes of padding. */
  1402. bad |= size_greater_than( 8, pad_count );
  1403. /* If the padding is valid, set plaintext_size to the number of
  1404. * remaining bytes after stripping the padding. If the padding
  1405. * is invalid, avoid leaking this fact through the size of the
  1406. * output: use the maximum message size that fits in the output
  1407. * buffer. Do it without branches to avoid leaking the padding
  1408. * validity through timing. RSA keys are small enough that all the
  1409. * size_t values involved fit in unsigned int. */
  1410. plaintext_size = if_int( bad,
  1411. (unsigned) plaintext_max_size,
  1412. (unsigned) ( ilen - pad_count - 3 ) );
  1413. /* Set output_too_large to 0 if the plaintext fits in the output
  1414. * buffer and to 1 otherwise. */
  1415. output_too_large = size_greater_than( plaintext_size,
  1416. plaintext_max_size );
  1417. /* Set ret without branches to avoid timing attacks. Return:
  1418. * - INVALID_PADDING if the padding is bad (bad != 0).
  1419. * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  1420. * plaintext does not fit in the output buffer.
  1421. * - 0 if the padding is correct. */
  1422. ret = - (int) if_int( bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
  1423. if_int( output_too_large, - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
  1424. 0 ) );
  1425. /* If the padding is bad or the plaintext is too large, zero the
  1426. * data that we're about to copy to the output buffer.
  1427. * We need to copy the same amount of data
  1428. * from the same buffer whether the padding is good or not to
  1429. * avoid leaking the padding validity through overall timing or
  1430. * through memory or cache access patterns. */
  1431. bad = all_or_nothing_int( bad | output_too_large );
  1432. for( i = 11; i < ilen; i++ )
  1433. buf[i] &= ~bad;
  1434. /* If the plaintext is too large, truncate it to the buffer size.
  1435. * Copy anyway to avoid revealing the length through timing, because
  1436. * revealing the length is as bad as revealing the padding validity
  1437. * for a Bleichenbacher attack. */
  1438. plaintext_size = if_int( output_too_large,
  1439. (unsigned) plaintext_max_size,
  1440. (unsigned) plaintext_size );
  1441. /* Move the plaintext to the leftmost position where it can start in
  1442. * the working buffer, i.e. make it start plaintext_max_size from
  1443. * the end of the buffer. Do this with a memory access trace that
  1444. * does not depend on the plaintext size. After this move, the
  1445. * starting location of the plaintext is no longer sensitive
  1446. * information. */
  1447. mem_move_to_left( buf + ilen - plaintext_max_size,
  1448. plaintext_max_size,
  1449. plaintext_max_size - plaintext_size );
  1450. /* Finally copy the decrypted plaintext plus trailing zeros into the output
  1451. * buffer. If output_max_len is 0, then output may be an invalid pointer
  1452. * and the result of memcpy() would be undefined; prevent undefined
  1453. * behavior making sure to depend only on output_max_len (the size of the
  1454. * user-provided output buffer), which is independent from plaintext
  1455. * length, validity of padding, success of the decryption, and other
  1456. * secrets. */
  1457. if( output_max_len != 0 )
  1458. memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
  1459. /* Report the amount of data we copied to the output buffer. In case
  1460. * of errors (bad padding or output too large), the value of *olen
  1461. * when this function returns is not specified. Making it equivalent
  1462. * to the good case limits the risks of leaking the padding validity. */
  1463. *olen = plaintext_size;
  1464. cleanup:
  1465. mbedtls_platform_zeroize( buf, sizeof( buf ) );
  1466. return( ret );
  1467. }
  1468. #endif /* MBEDTLS_PKCS1_V15 */
  1469. /*
  1470. * Do an RSA operation, then remove the message padding
  1471. */
  1472. int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
  1473. int (*f_rng)(void *, unsigned char *, size_t),
  1474. void *p_rng,
  1475. int mode, size_t *olen,
  1476. const unsigned char *input,
  1477. unsigned char *output,
  1478. size_t output_max_len)
  1479. {
  1480. RSA_VALIDATE_RET( ctx != NULL );
  1481. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1482. mode == MBEDTLS_RSA_PUBLIC );
  1483. RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1484. RSA_VALIDATE_RET( input != NULL );
  1485. RSA_VALIDATE_RET( olen != NULL );
  1486. switch( ctx->padding )
  1487. {
  1488. #if defined(MBEDTLS_PKCS1_V15)
  1489. case MBEDTLS_RSA_PKCS_V15:
  1490. return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,
  1491. input, output, output_max_len );
  1492. #endif
  1493. #if defined(MBEDTLS_PKCS1_V21)
  1494. case MBEDTLS_RSA_PKCS_V21:
  1495. return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,
  1496. olen, input, output,
  1497. output_max_len );
  1498. #endif
  1499. default:
  1500. return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1501. }
  1502. }
  1503. #if defined(MBEDTLS_PKCS1_V21)
  1504. static int rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
  1505. int (*f_rng)(void *, unsigned char *, size_t),
  1506. void *p_rng,
  1507. int mode,
  1508. mbedtls_md_type_t md_alg,
  1509. unsigned int hashlen,
  1510. const unsigned char *hash,
  1511. int saltlen,
  1512. unsigned char *sig )
  1513. {
  1514. size_t olen;
  1515. unsigned char *p = sig;
  1516. unsigned char *salt = NULL;
  1517. size_t slen, min_slen, hlen, offset = 0;
  1518. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1519. size_t msb;
  1520. const mbedtls_md_info_t *md_info;
  1521. mbedtls_md_context_t md_ctx;
  1522. RSA_VALIDATE_RET( ctx != NULL );
  1523. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1524. mode == MBEDTLS_RSA_PUBLIC );
  1525. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  1526. hashlen == 0 ) ||
  1527. hash != NULL );
  1528. RSA_VALIDATE_RET( sig != NULL );
  1529. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1530. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1531. if( f_rng == NULL )
  1532. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1533. olen = ctx->len;
  1534. if( md_alg != MBEDTLS_MD_NONE )
  1535. {
  1536. /* Gather length of hash to sign */
  1537. md_info = mbedtls_md_info_from_type( md_alg );
  1538. if( md_info == NULL )
  1539. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1540. hashlen = mbedtls_md_get_size( md_info );
  1541. }
  1542. md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  1543. if( md_info == NULL )
  1544. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1545. hlen = mbedtls_md_get_size( md_info );
  1546. if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY)
  1547. {
  1548. /* Calculate the largest possible salt length, up to the hash size.
  1549. * Normally this is the hash length, which is the maximum salt length
  1550. * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
  1551. * enough room, use the maximum salt length that fits. The constraint is
  1552. * that the hash length plus the salt length plus 2 bytes must be at most
  1553. * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
  1554. * (PKCS#1 v2.2) §9.1.1 step 3. */
  1555. min_slen = hlen - 2;
  1556. if( olen < hlen + min_slen + 2 )
  1557. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1558. else if( olen >= hlen + hlen + 2 )
  1559. slen = hlen;
  1560. else
  1561. slen = olen - hlen - 2;
  1562. }
  1563. else if ( (saltlen < 0) || (saltlen + hlen + 2 > olen) )
  1564. {
  1565. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1566. }
  1567. else
  1568. {
  1569. slen = (size_t) saltlen;
  1570. }
  1571. memset( sig, 0, olen );
  1572. /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
  1573. msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  1574. p += olen - hlen - slen - 2;
  1575. *p++ = 0x01;
  1576. /* Generate salt of length slen in place in the encoded message */
  1577. salt = p;
  1578. if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
  1579. return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_RSA_RNG_FAILED, ret ) );
  1580. p += slen;
  1581. mbedtls_md_init( &md_ctx );
  1582. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1583. goto exit;
  1584. /* Generate H = Hash( M' ) */
  1585. if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )
  1586. goto exit;
  1587. if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 )
  1588. goto exit;
  1589. if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 )
  1590. goto exit;
  1591. if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 )
  1592. goto exit;
  1593. if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 )
  1594. goto exit;
  1595. /* Compensate for boundary condition when applying mask */
  1596. if( msb % 8 == 0 )
  1597. offset = 1;
  1598. /* maskedDB: Apply dbMask to DB */
  1599. if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen,
  1600. &md_ctx ) ) != 0 )
  1601. goto exit;
  1602. msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  1603. sig[0] &= 0xFF >> ( olen * 8 - msb );
  1604. p += hlen;
  1605. *p++ = 0xBC;
  1606. exit:
  1607. mbedtls_md_free( &md_ctx );
  1608. if( ret != 0 )
  1609. return( ret );
  1610. return( ( mode == MBEDTLS_RSA_PUBLIC )
  1611. ? mbedtls_rsa_public( ctx, sig, sig )
  1612. : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) );
  1613. }
  1614. /*
  1615. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
  1616. * the option to pass in the salt length.
  1617. */
  1618. int mbedtls_rsa_rsassa_pss_sign_ext( mbedtls_rsa_context *ctx,
  1619. int (*f_rng)(void *, unsigned char *, size_t),
  1620. void *p_rng,
  1621. mbedtls_md_type_t md_alg,
  1622. unsigned int hashlen,
  1623. const unsigned char *hash,
  1624. int saltlen,
  1625. unsigned char *sig )
  1626. {
  1627. return rsa_rsassa_pss_sign( ctx, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, md_alg,
  1628. hashlen, hash, saltlen, sig );
  1629. }
  1630. /*
  1631. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
  1632. */
  1633. int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
  1634. int (*f_rng)(void *, unsigned char *, size_t),
  1635. void *p_rng,
  1636. int mode,
  1637. mbedtls_md_type_t md_alg,
  1638. unsigned int hashlen,
  1639. const unsigned char *hash,
  1640. unsigned char *sig )
  1641. {
  1642. return rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
  1643. hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig );
  1644. }
  1645. #endif /* MBEDTLS_PKCS1_V21 */
  1646. #if defined(MBEDTLS_PKCS1_V15)
  1647. /*
  1648. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
  1649. */
  1650. /* Construct a PKCS v1.5 encoding of a hashed message
  1651. *
  1652. * This is used both for signature generation and verification.
  1653. *
  1654. * Parameters:
  1655. * - md_alg: Identifies the hash algorithm used to generate the given hash;
  1656. * MBEDTLS_MD_NONE if raw data is signed.
  1657. * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.
  1658. * - hash: Buffer containing the hashed message or the raw data.
  1659. * - dst_len: Length of the encoded message.
  1660. * - dst: Buffer to hold the encoded message.
  1661. *
  1662. * Assumptions:
  1663. * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.
  1664. * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.
  1665. * - dst points to a buffer of size at least dst_len.
  1666. *
  1667. */
  1668. static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg,
  1669. unsigned int hashlen,
  1670. const unsigned char *hash,
  1671. size_t dst_len,
  1672. unsigned char *dst )
  1673. {
  1674. size_t oid_size = 0;
  1675. size_t nb_pad = dst_len;
  1676. unsigned char *p = dst;
  1677. const char *oid = NULL;
  1678. /* Are we signing hashed or raw data? */
  1679. if( md_alg != MBEDTLS_MD_NONE )
  1680. {
  1681. const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
  1682. if( md_info == NULL )
  1683. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1684. if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
  1685. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1686. hashlen = mbedtls_md_get_size( md_info );
  1687. /* Double-check that 8 + hashlen + oid_size can be used as a
  1688. * 1-byte ASN.1 length encoding and that there's no overflow. */
  1689. if( 8 + hashlen + oid_size >= 0x80 ||
  1690. 10 + hashlen < hashlen ||
  1691. 10 + hashlen + oid_size < 10 + hashlen )
  1692. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1693. /*
  1694. * Static bounds check:
  1695. * - Need 10 bytes for five tag-length pairs.
  1696. * (Insist on 1-byte length encodings to protect against variants of
  1697. * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
  1698. * - Need hashlen bytes for hash
  1699. * - Need oid_size bytes for hash alg OID.
  1700. */
  1701. if( nb_pad < 10 + hashlen + oid_size )
  1702. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1703. nb_pad -= 10 + hashlen + oid_size;
  1704. }
  1705. else
  1706. {
  1707. if( nb_pad < hashlen )
  1708. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1709. nb_pad -= hashlen;
  1710. }
  1711. /* Need space for signature header and padding delimiter (3 bytes),
  1712. * and 8 bytes for the minimal padding */
  1713. if( nb_pad < 3 + 8 )
  1714. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1715. nb_pad -= 3;
  1716. /* Now nb_pad is the amount of memory to be filled
  1717. * with padding, and at least 8 bytes long. */
  1718. /* Write signature header and padding */
  1719. *p++ = 0;
  1720. *p++ = MBEDTLS_RSA_SIGN;
  1721. memset( p, 0xFF, nb_pad );
  1722. p += nb_pad;
  1723. *p++ = 0;
  1724. /* Are we signing raw data? */
  1725. if( md_alg == MBEDTLS_MD_NONE )
  1726. {
  1727. memcpy( p, hash, hashlen );
  1728. return( 0 );
  1729. }
  1730. /* Signing hashed data, add corresponding ASN.1 structure
  1731. *
  1732. * DigestInfo ::= SEQUENCE {
  1733. * digestAlgorithm DigestAlgorithmIdentifier,
  1734. * digest Digest }
  1735. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  1736. * Digest ::= OCTET STRING
  1737. *
  1738. * Schematic:
  1739. * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
  1740. * TAG-NULL + LEN [ NULL ] ]
  1741. * TAG-OCTET + LEN [ HASH ] ]
  1742. */
  1743. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1744. *p++ = (unsigned char)( 0x08 + oid_size + hashlen );
  1745. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1746. *p++ = (unsigned char)( 0x04 + oid_size );
  1747. *p++ = MBEDTLS_ASN1_OID;
  1748. *p++ = (unsigned char) oid_size;
  1749. memcpy( p, oid, oid_size );
  1750. p += oid_size;
  1751. *p++ = MBEDTLS_ASN1_NULL;
  1752. *p++ = 0x00;
  1753. *p++ = MBEDTLS_ASN1_OCTET_STRING;
  1754. *p++ = (unsigned char) hashlen;
  1755. memcpy( p, hash, hashlen );
  1756. p += hashlen;
  1757. /* Just a sanity-check, should be automatic
  1758. * after the initial bounds check. */
  1759. if( p != dst + dst_len )
  1760. {
  1761. mbedtls_platform_zeroize( dst, dst_len );
  1762. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1763. }
  1764. return( 0 );
  1765. }
  1766. /*
  1767. * Do an RSA operation to sign the message digest
  1768. */
  1769. int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
  1770. int (*f_rng)(void *, unsigned char *, size_t),
  1771. void *p_rng,
  1772. int mode,
  1773. mbedtls_md_type_t md_alg,
  1774. unsigned int hashlen,
  1775. const unsigned char *hash,
  1776. unsigned char *sig )
  1777. {
  1778. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1779. unsigned char *sig_try = NULL, *verif = NULL;
  1780. RSA_VALIDATE_RET( ctx != NULL );
  1781. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1782. mode == MBEDTLS_RSA_PUBLIC );
  1783. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  1784. hashlen == 0 ) ||
  1785. hash != NULL );
  1786. RSA_VALIDATE_RET( sig != NULL );
  1787. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  1788. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1789. /*
  1790. * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
  1791. */
  1792. if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash,
  1793. ctx->len, sig ) ) != 0 )
  1794. return( ret );
  1795. /*
  1796. * Call respective RSA primitive
  1797. */
  1798. if( mode == MBEDTLS_RSA_PUBLIC )
  1799. {
  1800. /* Skip verification on a public key operation */
  1801. return( mbedtls_rsa_public( ctx, sig, sig ) );
  1802. }
  1803. /* Private key operation
  1804. *
  1805. * In order to prevent Lenstra's attack, make the signature in a
  1806. * temporary buffer and check it before returning it.
  1807. */
  1808. sig_try = mbedtls_calloc( 1, ctx->len );
  1809. if( sig_try == NULL )
  1810. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  1811. verif = mbedtls_calloc( 1, ctx->len );
  1812. if( verif == NULL )
  1813. {
  1814. mbedtls_free( sig_try );
  1815. return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  1816. }
  1817. MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) );
  1818. MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) );
  1819. if( mbedtls_safer_memcmp( verif, sig, ctx->len ) != 0 )
  1820. {
  1821. ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
  1822. goto cleanup;
  1823. }
  1824. memcpy( sig, sig_try, ctx->len );
  1825. cleanup:
  1826. mbedtls_free( sig_try );
  1827. mbedtls_free( verif );
  1828. return( ret );
  1829. }
  1830. #endif /* MBEDTLS_PKCS1_V15 */
  1831. /*
  1832. * Do an RSA operation to sign the message digest
  1833. */
  1834. int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
  1835. int (*f_rng)(void *, unsigned char *, size_t),
  1836. void *p_rng,
  1837. int mode,
  1838. mbedtls_md_type_t md_alg,
  1839. unsigned int hashlen,
  1840. const unsigned char *hash,
  1841. unsigned char *sig )
  1842. {
  1843. RSA_VALIDATE_RET( ctx != NULL );
  1844. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1845. mode == MBEDTLS_RSA_PUBLIC );
  1846. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  1847. hashlen == 0 ) ||
  1848. hash != NULL );
  1849. RSA_VALIDATE_RET( sig != NULL );
  1850. switch( ctx->padding )
  1851. {
  1852. #if defined(MBEDTLS_PKCS1_V15)
  1853. case MBEDTLS_RSA_PKCS_V15:
  1854. return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,
  1855. hashlen, hash, sig );
  1856. #endif
  1857. #if defined(MBEDTLS_PKCS1_V21)
  1858. case MBEDTLS_RSA_PKCS_V21:
  1859. return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
  1860. hashlen, hash, sig );
  1861. #endif
  1862. default:
  1863. return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1864. }
  1865. }
  1866. #if defined(MBEDTLS_PKCS1_V21)
  1867. /*
  1868. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  1869. */
  1870. int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
  1871. int (*f_rng)(void *, unsigned char *, size_t),
  1872. void *p_rng,
  1873. int mode,
  1874. mbedtls_md_type_t md_alg,
  1875. unsigned int hashlen,
  1876. const unsigned char *hash,
  1877. mbedtls_md_type_t mgf1_hash_id,
  1878. int expected_salt_len,
  1879. const unsigned char *sig )
  1880. {
  1881. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1882. size_t siglen;
  1883. unsigned char *p;
  1884. unsigned char *hash_start;
  1885. unsigned char result[MBEDTLS_MD_MAX_SIZE];
  1886. unsigned char zeros[8];
  1887. unsigned int hlen;
  1888. size_t observed_salt_len, msb;
  1889. const mbedtls_md_info_t *md_info;
  1890. mbedtls_md_context_t md_ctx;
  1891. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1892. RSA_VALIDATE_RET( ctx != NULL );
  1893. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1894. mode == MBEDTLS_RSA_PUBLIC );
  1895. RSA_VALIDATE_RET( sig != NULL );
  1896. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  1897. hashlen == 0 ) ||
  1898. hash != NULL );
  1899. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1900. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1901. siglen = ctx->len;
  1902. if( siglen < 16 || siglen > sizeof( buf ) )
  1903. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1904. ret = ( mode == MBEDTLS_RSA_PUBLIC )
  1905. ? mbedtls_rsa_public( ctx, sig, buf )
  1906. : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );
  1907. if( ret != 0 )
  1908. return( ret );
  1909. p = buf;
  1910. if( buf[siglen - 1] != 0xBC )
  1911. return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1912. if( md_alg != MBEDTLS_MD_NONE )
  1913. {
  1914. /* Gather length of hash to sign */
  1915. md_info = mbedtls_md_info_from_type( md_alg );
  1916. if( md_info == NULL )
  1917. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1918. hashlen = mbedtls_md_get_size( md_info );
  1919. }
  1920. md_info = mbedtls_md_info_from_type( mgf1_hash_id );
  1921. if( md_info == NULL )
  1922. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1923. hlen = mbedtls_md_get_size( md_info );
  1924. memset( zeros, 0, 8 );
  1925. /*
  1926. * Note: EMSA-PSS verification is over the length of N - 1 bits
  1927. */
  1928. msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  1929. if( buf[0] >> ( 8 - siglen * 8 + msb ) )
  1930. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1931. /* Compensate for boundary condition when applying mask */
  1932. if( msb % 8 == 0 )
  1933. {
  1934. p++;
  1935. siglen -= 1;
  1936. }
  1937. if( siglen < hlen + 2 )
  1938. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1939. hash_start = p + siglen - hlen - 1;
  1940. mbedtls_md_init( &md_ctx );
  1941. if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1942. goto exit;
  1943. ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx );
  1944. if( ret != 0 )
  1945. goto exit;
  1946. buf[0] &= 0xFF >> ( siglen * 8 - msb );
  1947. while( p < hash_start - 1 && *p == 0 )
  1948. p++;
  1949. if( *p++ != 0x01 )
  1950. {
  1951. ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1952. goto exit;
  1953. }
  1954. observed_salt_len = hash_start - p;
  1955. if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
  1956. observed_salt_len != (size_t) expected_salt_len )
  1957. {
  1958. ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1959. goto exit;
  1960. }
  1961. /*
  1962. * Generate H = Hash( M' )
  1963. */
  1964. ret = mbedtls_md_starts( &md_ctx );
  1965. if ( ret != 0 )
  1966. goto exit;
  1967. ret = mbedtls_md_update( &md_ctx, zeros, 8 );
  1968. if ( ret != 0 )
  1969. goto exit;
  1970. ret = mbedtls_md_update( &md_ctx, hash, hashlen );
  1971. if ( ret != 0 )
  1972. goto exit;
  1973. ret = mbedtls_md_update( &md_ctx, p, observed_salt_len );
  1974. if ( ret != 0 )
  1975. goto exit;
  1976. ret = mbedtls_md_finish( &md_ctx, result );
  1977. if ( ret != 0 )
  1978. goto exit;
  1979. if( memcmp( hash_start, result, hlen ) != 0 )
  1980. {
  1981. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  1982. goto exit;
  1983. }
  1984. exit:
  1985. mbedtls_md_free( &md_ctx );
  1986. return( ret );
  1987. }
  1988. /*
  1989. * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  1990. */
  1991. int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
  1992. int (*f_rng)(void *, unsigned char *, size_t),
  1993. void *p_rng,
  1994. int mode,
  1995. mbedtls_md_type_t md_alg,
  1996. unsigned int hashlen,
  1997. const unsigned char *hash,
  1998. const unsigned char *sig )
  1999. {
  2000. mbedtls_md_type_t mgf1_hash_id;
  2001. RSA_VALIDATE_RET( ctx != NULL );
  2002. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2003. mode == MBEDTLS_RSA_PUBLIC );
  2004. RSA_VALIDATE_RET( sig != NULL );
  2005. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  2006. hashlen == 0 ) ||
  2007. hash != NULL );
  2008. mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE )
  2009. ? (mbedtls_md_type_t) ctx->hash_id
  2010. : md_alg;
  2011. return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,
  2012. md_alg, hashlen, hash,
  2013. mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,
  2014. sig ) );
  2015. }
  2016. #endif /* MBEDTLS_PKCS1_V21 */
  2017. #if defined(MBEDTLS_PKCS1_V15)
  2018. /*
  2019. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
  2020. */
  2021. int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
  2022. int (*f_rng)(void *, unsigned char *, size_t),
  2023. void *p_rng,
  2024. int mode,
  2025. mbedtls_md_type_t md_alg,
  2026. unsigned int hashlen,
  2027. const unsigned char *hash,
  2028. const unsigned char *sig )
  2029. {
  2030. int ret = 0;
  2031. size_t sig_len;
  2032. unsigned char *encoded = NULL, *encoded_expected = NULL;
  2033. RSA_VALIDATE_RET( ctx != NULL );
  2034. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2035. mode == MBEDTLS_RSA_PUBLIC );
  2036. RSA_VALIDATE_RET( sig != NULL );
  2037. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  2038. hashlen == 0 ) ||
  2039. hash != NULL );
  2040. sig_len = ctx->len;
  2041. if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  2042. return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2043. /*
  2044. * Prepare expected PKCS1 v1.5 encoding of hash.
  2045. */
  2046. if( ( encoded = mbedtls_calloc( 1, sig_len ) ) == NULL ||
  2047. ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL )
  2048. {
  2049. ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2050. goto cleanup;
  2051. }
  2052. if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len,
  2053. encoded_expected ) ) != 0 )
  2054. goto cleanup;
  2055. /*
  2056. * Apply RSA primitive to get what should be PKCS1 encoded hash.
  2057. */
  2058. ret = ( mode == MBEDTLS_RSA_PUBLIC )
  2059. ? mbedtls_rsa_public( ctx, sig, encoded )
  2060. : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded );
  2061. if( ret != 0 )
  2062. goto cleanup;
  2063. /*
  2064. * Compare
  2065. */
  2066. if( ( ret = mbedtls_safer_memcmp( encoded, encoded_expected,
  2067. sig_len ) ) != 0 )
  2068. {
  2069. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2070. goto cleanup;
  2071. }
  2072. cleanup:
  2073. if( encoded != NULL )
  2074. {
  2075. mbedtls_platform_zeroize( encoded, sig_len );
  2076. mbedtls_free( encoded );
  2077. }
  2078. if( encoded_expected != NULL )
  2079. {
  2080. mbedtls_platform_zeroize( encoded_expected, sig_len );
  2081. mbedtls_free( encoded_expected );
  2082. }
  2083. return( ret );
  2084. }
  2085. #endif /* MBEDTLS_PKCS1_V15 */
  2086. /*
  2087. * Do an RSA operation and check the message digest
  2088. */
  2089. int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
  2090. int (*f_rng)(void *, unsigned char *, size_t),
  2091. void *p_rng,
  2092. int mode,
  2093. mbedtls_md_type_t md_alg,
  2094. unsigned int hashlen,
  2095. const unsigned char *hash,
  2096. const unsigned char *sig )
  2097. {
  2098. RSA_VALIDATE_RET( ctx != NULL );
  2099. RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2100. mode == MBEDTLS_RSA_PUBLIC );
  2101. RSA_VALIDATE_RET( sig != NULL );
  2102. RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE &&
  2103. hashlen == 0 ) ||
  2104. hash != NULL );
  2105. switch( ctx->padding )
  2106. {
  2107. #if defined(MBEDTLS_PKCS1_V15)
  2108. case MBEDTLS_RSA_PKCS_V15:
  2109. return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,
  2110. hashlen, hash, sig );
  2111. #endif
  2112. #if defined(MBEDTLS_PKCS1_V21)
  2113. case MBEDTLS_RSA_PKCS_V21:
  2114. return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,
  2115. hashlen, hash, sig );
  2116. #endif
  2117. default:
  2118. return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  2119. }
  2120. }
  2121. /*
  2122. * Copy the components of an RSA key
  2123. */
  2124. int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
  2125. {
  2126. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2127. RSA_VALIDATE_RET( dst != NULL );
  2128. RSA_VALIDATE_RET( src != NULL );
  2129. dst->len = src->len;
  2130. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) );
  2131. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) );
  2132. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) );
  2133. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) );
  2134. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) );
  2135. #if !defined(MBEDTLS_RSA_NO_CRT)
  2136. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) );
  2137. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) );
  2138. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) );
  2139. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) );
  2140. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) );
  2141. #endif
  2142. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) );
  2143. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) );
  2144. MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) );
  2145. dst->padding = src->padding;
  2146. dst->hash_id = src->hash_id;
  2147. cleanup:
  2148. if( ret != 0 )
  2149. mbedtls_rsa_free( dst );
  2150. return( ret );
  2151. }
  2152. /*
  2153. * Free the components of an RSA key
  2154. */
  2155. void mbedtls_rsa_free( mbedtls_rsa_context *ctx )
  2156. {
  2157. if( ctx == NULL )
  2158. return;
  2159. mbedtls_mpi_free( &ctx->Vi );
  2160. mbedtls_mpi_free( &ctx->Vf );
  2161. mbedtls_mpi_free( &ctx->RN );
  2162. mbedtls_mpi_free( &ctx->D );
  2163. mbedtls_mpi_free( &ctx->Q );
  2164. mbedtls_mpi_free( &ctx->P );
  2165. mbedtls_mpi_free( &ctx->E );
  2166. mbedtls_mpi_free( &ctx->N );
  2167. #if !defined(MBEDTLS_RSA_NO_CRT)
  2168. mbedtls_mpi_free( &ctx->RQ );
  2169. mbedtls_mpi_free( &ctx->RP );
  2170. mbedtls_mpi_free( &ctx->QP );
  2171. mbedtls_mpi_free( &ctx->DQ );
  2172. mbedtls_mpi_free( &ctx->DP );
  2173. #endif /* MBEDTLS_RSA_NO_CRT */
  2174. #if defined(MBEDTLS_THREADING_C)
  2175. /* Free the mutex, but only if it hasn't been freed already. */
  2176. if( ctx->ver != 0 )
  2177. {
  2178. mbedtls_mutex_free( &ctx->mutex );
  2179. ctx->ver = 0;
  2180. }
  2181. #endif
  2182. }
  2183. #endif /* !MBEDTLS_RSA_ALT */
  2184. #if defined(MBEDTLS_SELF_TEST)
  2185. #include "mbedtls/sha1.h"
  2186. #if 1 //NXP TBD add test for bigger key
  2187. /*
  2188. * Example RSA-1024 keypair, for test purposes
  2189. */
  2190. #define KEY_LEN 128
  2191. #define RSA_N "9292758453063D803DD603D5E777D788" \
  2192. "8ED1D5BF35786190FA2F23EBC0848AEA" \
  2193. "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
  2194. "7130B9CED7ACDF54CFC7555AC14EEBAB" \
  2195. "93A89813FBF3C4F8066D2D800F7C38A8" \
  2196. "1AE31942917403FF4946B0A83D3D3E05" \
  2197. "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
  2198. "5E94BB77B07507233A0BC7BAC8F90F79"
  2199. #define RSA_E "10001"
  2200. #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
  2201. "66CA472BC44D253102F8B4A9D3BFA750" \
  2202. "91386C0077937FE33FA3252D28855837" \
  2203. "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
  2204. "DF79C5CE07EE72C7F123142198164234" \
  2205. "CABB724CF78B8173B9F880FC86322407" \
  2206. "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
  2207. "071513A1E85B5DFA031F21ECAE91A34D"
  2208. #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
  2209. "2C01CAD19EA484A87EA4377637E75500" \
  2210. "FCB2005C5C7DD6EC4AC023CDA285D796" \
  2211. "C3D9E75E1EFC42488BB4F1D13AC30A57"
  2212. #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
  2213. "E211C2B9E5DB1ED0BF61D0D9899620F4" \
  2214. "910E4168387E3C30AA1E00C339A79508" \
  2215. "8452DD96A9A5EA5D9DCA68DA636032AF"
  2216. #endif
  2217. #define PT_LEN 24
  2218. #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
  2219. "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
  2220. #if defined(MBEDTLS_PKCS1_V15)
  2221. static int myrand( void *rng_state, unsigned char *output, size_t len )
  2222. {
  2223. #if !defined(__OpenBSD__) && !defined(__NetBSD__)
  2224. size_t i;
  2225. if( rng_state != NULL )
  2226. rng_state = NULL;
  2227. for( i = 0; i < len; ++i )
  2228. output[i] = rand();
  2229. #else
  2230. if( rng_state != NULL )
  2231. rng_state = NULL;
  2232. arc4random_buf( output, len );
  2233. #endif /* !OpenBSD && !NetBSD */
  2234. return( 0 );
  2235. }
  2236. #endif /* MBEDTLS_PKCS1_V15 */
  2237. /*
  2238. * Checkup routine
  2239. */
  2240. int mbedtls_rsa_self_test( int verbose )
  2241. #if 1 //NXP TBD add test for bigger key
  2242. {
  2243. int ret = 0;
  2244. #if defined(MBEDTLS_PKCS1_V15)
  2245. size_t len;
  2246. mbedtls_rsa_context rsa;
  2247. unsigned char rsa_plaintext[PT_LEN];
  2248. unsigned char rsa_decrypted[PT_LEN];
  2249. unsigned char rsa_ciphertext[KEY_LEN];
  2250. #if defined(MBEDTLS_SHA1_C)
  2251. unsigned char sha1sum[20];
  2252. #endif
  2253. mbedtls_mpi K;
  2254. mbedtls_mpi_init( &K );
  2255. mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
  2256. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N ) );
  2257. MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) );
  2258. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P ) );
  2259. MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) );
  2260. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q ) );
  2261. MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) );
  2262. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D ) );
  2263. MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) );
  2264. MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E ) );
  2265. MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) );
  2266. MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) );
  2267. if( verbose != 0 )
  2268. mbedtls_printf( " RSA key validation: " );
  2269. if( mbedtls_rsa_check_pubkey( &rsa ) != 0 ||
  2270. mbedtls_rsa_check_privkey( &rsa ) != 0 )
  2271. {
  2272. if( verbose != 0 )
  2273. mbedtls_printf( "failed\n" );
  2274. ret = 1;
  2275. goto cleanup;
  2276. }
  2277. if( verbose != 0 )
  2278. mbedtls_printf( "passed\n PKCS#1 encryption : " );
  2279. memcpy( rsa_plaintext, RSA_PT, PT_LEN );
  2280. if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC,
  2281. PT_LEN, rsa_plaintext,
  2282. rsa_ciphertext ) != 0 )
  2283. {
  2284. if( verbose != 0 )
  2285. mbedtls_printf( "failed\n" );
  2286. ret = 1;
  2287. goto cleanup;
  2288. }
  2289. if( verbose != 0 )
  2290. mbedtls_printf( "passed\n PKCS#1 decryption : " );
  2291. if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE,
  2292. &len, rsa_ciphertext, rsa_decrypted,
  2293. sizeof(rsa_decrypted) ) != 0 )
  2294. {
  2295. if( verbose != 0 )
  2296. mbedtls_printf( "failed\n" );
  2297. ret = 1;
  2298. goto cleanup;
  2299. }
  2300. if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
  2301. {
  2302. if( verbose != 0 )
  2303. mbedtls_printf( "failed\n" );
  2304. ret = 1;
  2305. goto cleanup;
  2306. }
  2307. if( verbose != 0 )
  2308. mbedtls_printf( "passed\n" );
  2309. #if defined(MBEDTLS_SHA1_C)
  2310. if( verbose != 0 )
  2311. mbedtls_printf( " PKCS#1 data sign : " );
  2312. if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 )
  2313. {
  2314. if( verbose != 0 )
  2315. mbedtls_printf( "failed\n" );
  2316. return( 1 );
  2317. }
  2318. if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL,
  2319. MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
  2320. sha1sum, rsa_ciphertext ) != 0 )
  2321. {
  2322. if( verbose != 0 )
  2323. mbedtls_printf( "failed\n" );
  2324. ret = 1;
  2325. goto cleanup;
  2326. }
  2327. if( verbose != 0 )
  2328. mbedtls_printf( "passed\n PKCS#1 sig. verify: " );
  2329. if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL,
  2330. MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
  2331. sha1sum, rsa_ciphertext ) != 0 )
  2332. {
  2333. if( verbose != 0 )
  2334. mbedtls_printf( "failed\n" );
  2335. ret = 1;
  2336. goto cleanup;
  2337. }
  2338. if( verbose != 0 )
  2339. mbedtls_printf( "passed\n" );
  2340. #endif /* MBEDTLS_SHA1_C */
  2341. if( verbose != 0 )
  2342. mbedtls_printf( "\n" );
  2343. cleanup:
  2344. mbedtls_mpi_free( &K );
  2345. mbedtls_rsa_free( &rsa );
  2346. #else /* MBEDTLS_PKCS1_V15 */
  2347. ((void) verbose);
  2348. #endif /* MBEDTLS_PKCS1_V15 */
  2349. return( ret );
  2350. }
  2351. #else
  2352. {
  2353. int ret = 0;
  2354. #if defined(MBEDTLS_PKCS1_V15)
  2355. size_t len;
  2356. mbedtls_pk_context pk;
  2357. mbedtls_rsa_context *rsa;
  2358. unsigned char rsa_plaintext[PT_LEN];
  2359. unsigned char rsa_decrypted[PT_LEN];
  2360. #if defined(MBEDTLS_SHA1_C)
  2361. unsigned char sha1sum[20];
  2362. #endif
  2363. #if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) \
  2364. || (defined(FREESCALE_PKHA_INT_MAX_BYTES) && (FREESCALE_PKHA_INT_MAX_BYTES >= ((4096 / 8) * 2)))
  2365. unsigned char rsa_ciphertext[4096 / 8];
  2366. const char *rsa_keys[] = { RSA_PRIVATE_KEY_1024, RSA_PRIVATE_KEY_2048, RSA_PRIVATE_KEY_4096 };
  2367. #elif defined(FREESCALE_PKHA_INT_MAX_BYTES) && (FREESCALE_PKHA_INT_MAX_BYTES >= ((2048 / 8) * 2))
  2368. unsigned char rsa_ciphertext[2048 / 8];
  2369. const char *rsa_keys[] = { RSA_PRIVATE_KEY_1024, RSA_PRIVATE_KEY_2048 };
  2370. #else
  2371. unsigned char rsa_ciphertext[1024 / 8];
  2372. const char *rsa_keys[] = { RSA_PRIVATE_KEY_1024 };
  2373. #endif
  2374. size_t i;
  2375. for (i = 0; i < sizeof(rsa_keys) / sizeof(rsa_keys[0]); i++)
  2376. {
  2377. mbedtls_pk_init(&pk);
  2378. if( verbose != 0 )
  2379. mbedtls_printf( " RSA parse key #%d : ", i + 1 );
  2380. MBEDTLS_MPI_CHK( mbedtls_pk_parse_key(&pk, (const unsigned char *)rsa_keys[i], strlen(rsa_keys[i]) + 1, NULL, 0) );
  2381. rsa = mbedtls_pk_rsa(pk);
  2382. if( verbose != 0 )
  2383. mbedtls_printf( "passed\n\r RSA-%d key validation: ", mbedtls_pk_get_bitlen( &pk ) );
  2384. MBEDTLS_MPI_CHK( mbedtls_rsa_check_pubkey( rsa ) );
  2385. MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( rsa ) );
  2386. if( verbose != 0 )
  2387. mbedtls_printf( "passed\n\r PKCS#1 encryption : " );
  2388. memcpy( rsa_plaintext, RSA_PT, PT_LEN );
  2389. MBEDTLS_MPI_CHK( mbedtls_rsa_pkcs1_encrypt( rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC, PT_LEN,
  2390. rsa_plaintext, rsa_ciphertext ) );
  2391. if( verbose != 0 )
  2392. mbedtls_printf( "passed\n\r PKCS#1 decryption : " );
  2393. MBEDTLS_MPI_CHK( mbedtls_rsa_pkcs1_decrypt( rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, &len,
  2394. rsa_ciphertext, rsa_decrypted,
  2395. sizeof(rsa_decrypted) ) );
  2396. MBEDTLS_MPI_CHK( memcmp( rsa_decrypted, rsa_plaintext, len ) );
  2397. if( verbose != 0 )
  2398. mbedtls_printf( "passed\n\r" );
  2399. #if defined(MBEDTLS_SHA1_C)
  2400. if( verbose != 0 )
  2401. mbedtls_printf( " PKCS#1 data sign : " );
  2402. mbedtls_sha1( rsa_plaintext, PT_LEN, sha1sum );
  2403. MBEDTLS_MPI_CHK( mbedtls_rsa_pkcs1_sign( rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
  2404. sha1sum, rsa_ciphertext ) );
  2405. if( verbose != 0 )
  2406. mbedtls_printf( "passed\n\r PKCS#1 sig. verify : " );
  2407. MBEDTLS_MPI_CHK( mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
  2408. sha1sum, rsa_ciphertext ) );
  2409. if( verbose != 0 )
  2410. mbedtls_printf( "passed\n\r" );
  2411. #endif /* MBEDTLS_SHA1_C */
  2412. if( verbose != 0 )
  2413. mbedtls_printf( "\n\r" );
  2414. cleanup:
  2415. mbedtls_pk_free( &pk );
  2416. if( ret != 0 )
  2417. {
  2418. if( verbose != 0 )
  2419. mbedtls_printf( "failed\n\r" );
  2420. return( 1 );
  2421. }
  2422. #else /* MBEDTLS_PKCS1_V15 */
  2423. ((void) verbose);
  2424. #endif /* MBEDTLS_PKCS1_V15 */
  2425. }
  2426. return( 0 );
  2427. }
  2428. #endif
  2429. #endif /* MBEDTLS_SELF_TEST */
  2430. #endif /* MBEDTLS_RSA_C */