rsa.c 83 KB

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