2
0

rsa.c 85 KB

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