rsa.c 78 KB

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