rsa.c 78 KB

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