rsa.c 85 KB

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