rsa.c 85 KB

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