rsa.c 83 KB

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