rsa.c 74 KB

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