rsa.c 74 KB

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