Line data Source code
1 : /* rsa.c - RSA implementation
2 : * Copyright (C) 1997, 1998, 1999 by Werner Koch (dd9jn)
3 : * Copyright (C) 2000, 2001, 2002, 2003, 2008 Free Software Foundation, Inc.
4 : *
5 : * This file is part of Libgcrypt.
6 : *
7 : * Libgcrypt is free software; you can redistribute it and/or modify
8 : * it under the terms of the GNU Lesser General Public License as
9 : * published by the Free Software Foundation; either version 2.1 of
10 : * the License, or (at your option) any later version.
11 : *
12 : * Libgcrypt is distributed in the hope that it will be useful,
13 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 : * GNU Lesser General Public License for more details.
16 : *
17 : * You should have received a copy of the GNU Lesser General Public
18 : * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 : */
20 :
21 : /* This code uses an algorithm protected by U.S. Patent #4,405,829
22 : which expired on September 20, 2000. The patent holder placed that
23 : patent into the public domain on Sep 6th, 2000.
24 : */
25 :
26 : #include <config.h>
27 : #include <stdio.h>
28 : #include <stdlib.h>
29 : #include <string.h>
30 : #include <errno.h>
31 :
32 : #include "g10lib.h"
33 : #include "mpi.h"
34 : #include "cipher.h"
35 : #include "pubkey-internal.h"
36 :
37 :
38 : typedef struct
39 : {
40 : gcry_mpi_t n; /* modulus */
41 : gcry_mpi_t e; /* exponent */
42 : } RSA_public_key;
43 :
44 :
45 : typedef struct
46 : {
47 : gcry_mpi_t n; /* public modulus */
48 : gcry_mpi_t e; /* public exponent */
49 : gcry_mpi_t d; /* exponent */
50 : gcry_mpi_t p; /* prime p. */
51 : gcry_mpi_t q; /* prime q. */
52 : gcry_mpi_t u; /* inverse of p mod q. */
53 : } RSA_secret_key;
54 :
55 :
56 : static const char *rsa_names[] =
57 : {
58 : "rsa",
59 : "openpgp-rsa",
60 : "oid.1.2.840.113549.1.1.1",
61 : NULL,
62 : };
63 :
64 :
65 : /* A sample 2048 bit RSA key used for the selftests. */
66 : static const char sample_secret_key[] =
67 : " (private-key"
68 : " (rsa"
69 : " (n #009F56231A3D82E3E7D613D59D53E9AB921BEF9F08A782AED0B6E46ADBC853EC"
70 : " 7C71C422435A3CD8FA0DB9EFD55CD3295BADC4E8E2E2B94E15AE82866AB8ADE8"
71 : " 7E469FAE76DC3577DE87F1F419C4EB41123DFAF8D16922D5EDBAD6E9076D5A1C"
72 : " 958106F0AE5E2E9193C6B49124C64C2A241C4075D4AF16299EB87A6585BAE917"
73 : " DEF27FCDD165764D069BC18D16527B29DAAB549F7BBED4A7C6A842D203ED6613"
74 : " 6E2411744E432CD26D940132F25874483DCAEECDFD95744819CBCF1EA810681C"
75 : " 42907EBCB1C7EAFBE75C87EC32C5413EA10476545D3FC7B2ADB1B66B7F200918"
76 : " 664B0E5261C2895AA28B0DE321E921B3F877172CCCAB81F43EF98002916156F6CB#)"
77 : " (e #010001#)"
78 : " (d #07EF82500C403899934FE993AC5A36F14FF2DF38CF1EF315F205EE4C83EDAA19"
79 : " 8890FC23DE9AA933CAFB37B6A8A8DBA675411958337287310D3FF2F1DDC0CB93"
80 : " 7E70F57F75F833C021852B631D2B9A520E4431A03C5C3FCB5742DCD841D9FB12"
81 : " 771AA1620DCEC3F1583426066ED9DC3F7028C5B59202C88FDF20396E2FA0EC4F"
82 : " 5A22D9008F3043673931BC14A5046D6327398327900867E39CC61B2D1AFE2F48"
83 : " EC8E1E3861C68D257D7425F4E6F99ABD77D61F10CA100EFC14389071831B33DD"
84 : " 69CC8EABEF860D1DC2AAA84ABEAE5DFC91BC124DAF0F4C8EF5BBEA436751DE84"
85 : " 3A8063E827A024466F44C28614F93B0732A100D4A0D86D532FE1E22C7725E401#)"
86 : " (p #00C29D438F115825779631CD665A5739367F3E128ADC29766483A46CA80897E0"
87 : " 79B32881860B8F9A6A04C2614A904F6F2578DAE13EA67CD60AE3D0AA00A1FF9B"
88 : " 441485E44B2DC3D0B60260FBFE073B5AC72FAF67964DE15C8212C389D20DB9CF"
89 : " 54AF6AEF5C4196EAA56495DD30CF709F499D5AB30CA35E086C2A1589D6283F1783#)"
90 : " (q #00D1984135231CB243FE959C0CBEF551EDD986AD7BEDF71EDF447BE3DA27AF46"
91 : " 79C974A6FA69E4D52FE796650623DE70622862713932AA2FD9F2EC856EAEAA77"
92 : " 88B4EA6084DC81C902F014829B18EA8B2666EC41586818E0589E18876065F97E"
93 : " 8D22CE2DA53A05951EC132DCEF41E70A9C35F4ACC268FFAC2ADF54FA1DA110B919#)"
94 : " (u #67CF0FD7635205DD80FA814EE9E9C267C17376BF3209FB5D1BC42890D2822A04"
95 : " 479DAF4D5B6ED69D0F8D1AF94164D07F8CD52ECEFE880641FA0F41DDAB1785E4"
96 : " A37A32F997A516480B4CD4F6482B9466A1765093ED95023CA32D5EDC1E34CEE9"
97 : " AF595BC51FE43C4BF810FA225AF697FB473B83815966188A4312C048B885E3F7#)))";
98 :
99 : /* A sample 2048 bit RSA key used for the selftests (public only). */
100 : static const char sample_public_key[] =
101 : " (public-key"
102 : " (rsa"
103 : " (n #009F56231A3D82E3E7D613D59D53E9AB921BEF9F08A782AED0B6E46ADBC853EC"
104 : " 7C71C422435A3CD8FA0DB9EFD55CD3295BADC4E8E2E2B94E15AE82866AB8ADE8"
105 : " 7E469FAE76DC3577DE87F1F419C4EB41123DFAF8D16922D5EDBAD6E9076D5A1C"
106 : " 958106F0AE5E2E9193C6B49124C64C2A241C4075D4AF16299EB87A6585BAE917"
107 : " DEF27FCDD165764D069BC18D16527B29DAAB549F7BBED4A7C6A842D203ED6613"
108 : " 6E2411744E432CD26D940132F25874483DCAEECDFD95744819CBCF1EA810681C"
109 : " 42907EBCB1C7EAFBE75C87EC32C5413EA10476545D3FC7B2ADB1B66B7F200918"
110 : " 664B0E5261C2895AA28B0DE321E921B3F877172CCCAB81F43EF98002916156F6CB#)"
111 : " (e #010001#)))";
112 :
113 :
114 : static int test_keys (RSA_secret_key *sk, unsigned nbits);
115 : static int check_secret_key (RSA_secret_key *sk);
116 : static void public (gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *skey);
117 : static void secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey);
118 : static unsigned int rsa_get_nbits (gcry_sexp_t parms);
119 :
120 :
121 : /* Check that a freshly generated key actually works. Returns 0 on success. */
122 : static int
123 39 : test_keys (RSA_secret_key *sk, unsigned int nbits)
124 : {
125 39 : int result = -1; /* Default to failure. */
126 : RSA_public_key pk;
127 39 : gcry_mpi_t plaintext = mpi_new (nbits);
128 39 : gcry_mpi_t ciphertext = mpi_new (nbits);
129 39 : gcry_mpi_t decr_plaintext = mpi_new (nbits);
130 39 : gcry_mpi_t signature = mpi_new (nbits);
131 :
132 : /* Put the relevant parameters into a public key structure. */
133 39 : pk.n = sk->n;
134 39 : pk.e = sk->e;
135 :
136 : /* Create a random plaintext. */
137 39 : _gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
138 :
139 : /* Encrypt using the public key. */
140 39 : public (ciphertext, plaintext, &pk);
141 :
142 : /* Check that the cipher text does not match the plaintext. */
143 39 : if (!mpi_cmp (ciphertext, plaintext))
144 0 : goto leave; /* Ciphertext is identical to the plaintext. */
145 :
146 : /* Decrypt using the secret key. */
147 39 : secret (decr_plaintext, ciphertext, sk);
148 :
149 : /* Check that the decrypted plaintext matches the original plaintext. */
150 39 : if (mpi_cmp (decr_plaintext, plaintext))
151 0 : goto leave; /* Plaintext does not match. */
152 :
153 : /* Create another random plaintext as data for signature checking. */
154 39 : _gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
155 :
156 : /* Use the RSA secret function to create a signature of the plaintext. */
157 39 : secret (signature, plaintext, sk);
158 :
159 : /* Use the RSA public function to verify this signature. */
160 39 : public (decr_plaintext, signature, &pk);
161 39 : if (mpi_cmp (decr_plaintext, plaintext))
162 0 : goto leave; /* Signature does not match. */
163 :
164 : /* Modify the signature and check that the signing fails. */
165 39 : mpi_add_ui (signature, signature, 1);
166 39 : public (decr_plaintext, signature, &pk);
167 39 : if (!mpi_cmp (decr_plaintext, plaintext))
168 0 : goto leave; /* Signature matches but should not. */
169 :
170 39 : result = 0; /* All tests succeeded. */
171 :
172 : leave:
173 39 : _gcry_mpi_release (signature);
174 39 : _gcry_mpi_release (decr_plaintext);
175 39 : _gcry_mpi_release (ciphertext);
176 39 : _gcry_mpi_release (plaintext);
177 39 : return result;
178 : }
179 :
180 :
181 : /* Callback used by the prime generation to test whether the exponent
182 : is suitable. Returns 0 if the test has been passed. */
183 : static int
184 64 : check_exponent (void *arg, gcry_mpi_t a)
185 : {
186 64 : gcry_mpi_t e = arg;
187 : gcry_mpi_t tmp;
188 : int result;
189 :
190 64 : mpi_sub_ui (a, a, 1);
191 64 : tmp = _gcry_mpi_alloc_like (a);
192 64 : result = !mpi_gcd(tmp, e, a); /* GCD is not 1. */
193 64 : _gcry_mpi_release (tmp);
194 64 : mpi_add_ui (a, a, 1);
195 64 : return result;
196 : }
197 :
198 : /****************
199 : * Generate a key pair with a key of size NBITS.
200 : * USE_E = 0 let Libcgrypt decide what exponent to use.
201 : * = 1 request the use of a "secure" exponent; this is required by some
202 : * specification to be 65537.
203 : * > 2 Use this public exponent. If the given exponent
204 : * is not odd one is internally added to it.
205 : * TRANSIENT_KEY: If true, generate the primes using the standard RNG.
206 : * Returns: 2 structures filled with all needed values
207 : */
208 : static gpg_err_code_t
209 33 : generate_std (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e,
210 : int transient_key)
211 : {
212 : gcry_mpi_t p, q; /* the two primes */
213 : gcry_mpi_t d; /* the private key */
214 : gcry_mpi_t u;
215 : gcry_mpi_t t1, t2;
216 : gcry_mpi_t n; /* the public key */
217 : gcry_mpi_t e; /* the exponent */
218 : gcry_mpi_t phi; /* helper: (p-1)(q-1) */
219 : gcry_mpi_t g;
220 : gcry_mpi_t f;
221 : gcry_random_level_t random_level;
222 :
223 33 : if (fips_mode ())
224 : {
225 0 : if (nbits < 1024)
226 0 : return GPG_ERR_INV_VALUE;
227 0 : if (transient_key)
228 0 : return GPG_ERR_INV_VALUE;
229 : }
230 :
231 : /* The random quality depends on the transient_key flag. */
232 33 : random_level = transient_key ? GCRY_STRONG_RANDOM : GCRY_VERY_STRONG_RANDOM;
233 :
234 : /* Make sure that nbits is even so that we generate p, q of equal size. */
235 33 : if ( (nbits&1) )
236 0 : nbits++;
237 :
238 33 : if (use_e == 1) /* Alias for a secure value */
239 0 : use_e = 65537; /* as demanded by Sphinx. */
240 :
241 : /* Public exponent:
242 : In general we use 41 as this is quite fast and more secure than the
243 : commonly used 17. Benchmarking the RSA verify function
244 : with a 1024 bit key yields (2001-11-08):
245 : e=17 0.54 ms
246 : e=41 0.75 ms
247 : e=257 0.95 ms
248 : e=65537 1.80 ms
249 : */
250 33 : e = mpi_alloc( (32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
251 33 : if (!use_e)
252 1 : mpi_set_ui (e, 41); /* This is a reasonable secure and fast value */
253 : else
254 : {
255 32 : use_e |= 1; /* make sure this is odd */
256 32 : mpi_set_ui (e, use_e);
257 : }
258 :
259 33 : n = mpi_new (nbits);
260 :
261 33 : p = q = NULL;
262 : do
263 : {
264 : /* select two (very secret) primes */
265 33 : if (p)
266 0 : _gcry_mpi_release (p);
267 33 : if (q)
268 0 : _gcry_mpi_release (q);
269 33 : if (use_e)
270 : { /* Do an extra test to ensure that the given exponent is
271 : suitable. */
272 32 : p = _gcry_generate_secret_prime (nbits/2, random_level,
273 : check_exponent, e);
274 32 : q = _gcry_generate_secret_prime (nbits/2, random_level,
275 : check_exponent, e);
276 : }
277 : else
278 : { /* We check the exponent later. */
279 1 : p = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
280 1 : q = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
281 : }
282 33 : if (mpi_cmp (p, q) > 0 ) /* p shall be smaller than q (for calc of u)*/
283 15 : mpi_swap(p,q);
284 : /* calculate the modulus */
285 33 : mpi_mul( n, p, q );
286 : }
287 33 : while ( mpi_get_nbits(n) != nbits );
288 :
289 : /* calculate Euler totient: phi = (p-1)(q-1) */
290 33 : t1 = mpi_alloc_secure( mpi_get_nlimbs(p) );
291 33 : t2 = mpi_alloc_secure( mpi_get_nlimbs(p) );
292 33 : phi = mpi_snew ( nbits );
293 33 : g = mpi_snew ( nbits );
294 33 : f = mpi_snew ( nbits );
295 33 : mpi_sub_ui( t1, p, 1 );
296 33 : mpi_sub_ui( t2, q, 1 );
297 33 : mpi_mul( phi, t1, t2 );
298 33 : mpi_gcd (g, t1, t2);
299 33 : mpi_fdiv_q(f, phi, g);
300 :
301 66 : while (!mpi_gcd(t1, e, phi)) /* (while gcd is not 1) */
302 : {
303 0 : if (use_e)
304 0 : BUG (); /* The prime generator already made sure that we
305 : never can get to here. */
306 0 : mpi_add_ui (e, e, 2);
307 : }
308 :
309 : /* calculate the secret key d = e^1 mod phi */
310 33 : d = mpi_snew ( nbits );
311 33 : mpi_invm (d, e, f );
312 : /* calculate the inverse of p and q (used for chinese remainder theorem)*/
313 33 : u = mpi_snew ( nbits );
314 33 : mpi_invm(u, p, q );
315 :
316 33 : if( DBG_CIPHER )
317 : {
318 0 : log_mpidump(" p= ", p );
319 0 : log_mpidump(" q= ", q );
320 0 : log_mpidump("phi= ", phi );
321 0 : log_mpidump(" g= ", g );
322 0 : log_mpidump(" f= ", f );
323 0 : log_mpidump(" n= ", n );
324 0 : log_mpidump(" e= ", e );
325 0 : log_mpidump(" d= ", d );
326 0 : log_mpidump(" u= ", u );
327 : }
328 :
329 33 : _gcry_mpi_release (t1);
330 33 : _gcry_mpi_release (t2);
331 33 : _gcry_mpi_release (phi);
332 33 : _gcry_mpi_release (f);
333 33 : _gcry_mpi_release (g);
334 :
335 33 : sk->n = n;
336 33 : sk->e = e;
337 33 : sk->p = p;
338 33 : sk->q = q;
339 33 : sk->d = d;
340 33 : sk->u = u;
341 :
342 : /* Now we can test our keys. */
343 33 : if (test_keys (sk, nbits - 64))
344 : {
345 0 : _gcry_mpi_release (sk->n); sk->n = NULL;
346 0 : _gcry_mpi_release (sk->e); sk->e = NULL;
347 0 : _gcry_mpi_release (sk->p); sk->p = NULL;
348 0 : _gcry_mpi_release (sk->q); sk->q = NULL;
349 0 : _gcry_mpi_release (sk->d); sk->d = NULL;
350 0 : _gcry_mpi_release (sk->u); sk->u = NULL;
351 0 : fips_signal_error ("self-test after key generation failed");
352 0 : return GPG_ERR_SELFTEST_FAILED;
353 : }
354 :
355 33 : return 0;
356 : }
357 :
358 :
359 : /****************
360 : * Generate a key pair with a key of size NBITS.
361 : * USE_E = 0 let Libcgrypt decide what exponent to use.
362 : * = 1 request the use of a "secure" exponent; this is required by some
363 : * specification to be 65537.
364 : * > 2 Use this public exponent. If the given exponent
365 : * is not odd one is internally added to it.
366 : * TESTPARMS: If set, do not generate but test whether the p,q is probably prime
367 : * Returns key with zeroes to not break code calling this function.
368 : * TRANSIENT_KEY: If true, generate the primes using the standard RNG.
369 : * Returns: 2 structures filled with all needed values
370 : */
371 : static gpg_err_code_t
372 0 : generate_fips (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e,
373 : gcry_sexp_t testparms, int transient_key)
374 : {
375 : gcry_mpi_t p, q; /* the two primes */
376 : gcry_mpi_t d; /* the private key */
377 : gcry_mpi_t u;
378 : gcry_mpi_t p1, q1;
379 : gcry_mpi_t n; /* the public key */
380 : gcry_mpi_t e; /* the exponent */
381 : gcry_mpi_t g;
382 : gcry_mpi_t minp;
383 : gcry_mpi_t diff, mindiff;
384 : gcry_random_level_t random_level;
385 0 : unsigned int pbits = nbits/2;
386 : unsigned int i;
387 : int pqswitch;
388 0 : gpg_err_code_t ec = GPG_ERR_NO_PRIME;
389 :
390 0 : if (nbits < 1024 || (nbits & 0x1FF))
391 0 : return GPG_ERR_INV_VALUE;
392 0 : if (_gcry_enforced_fips_mode() && nbits != 2048 && nbits != 3072)
393 0 : return GPG_ERR_INV_VALUE;
394 :
395 : /* The random quality depends on the transient_key flag. */
396 0 : random_level = transient_key ? GCRY_STRONG_RANDOM : GCRY_VERY_STRONG_RANDOM;
397 :
398 0 : if (testparms)
399 : {
400 : /* Parameters to derive the key are given. */
401 : /* Note that we explicitly need to setup the values of tbl
402 : because some compilers (e.g. OpenWatcom, IRIX) don't allow to
403 : initialize a structure with automatic variables. */
404 0 : struct { const char *name; gcry_mpi_t *value; } tbl[] = {
405 : { "e" },
406 : { "p" },
407 : { "q" },
408 : { NULL }
409 : };
410 : int idx;
411 : gcry_sexp_t oneparm;
412 :
413 0 : tbl[0].value = &e;
414 0 : tbl[1].value = &p;
415 0 : tbl[2].value = &q;
416 :
417 0 : for (idx=0; tbl[idx].name; idx++)
418 : {
419 0 : oneparm = sexp_find_token (testparms, tbl[idx].name, 0);
420 0 : if (oneparm)
421 : {
422 0 : *tbl[idx].value = sexp_nth_mpi (oneparm, 1, GCRYMPI_FMT_USG);
423 0 : sexp_release (oneparm);
424 : }
425 : }
426 0 : for (idx=0; tbl[idx].name; idx++)
427 0 : if (!*tbl[idx].value)
428 0 : break;
429 0 : if (tbl[idx].name)
430 : {
431 : /* At least one parameter is missing. */
432 0 : for (idx=0; tbl[idx].name; idx++)
433 0 : _gcry_mpi_release (*tbl[idx].value);
434 0 : return GPG_ERR_MISSING_VALUE;
435 : }
436 : }
437 : else
438 : {
439 0 : if (use_e < 65537)
440 0 : use_e = 65537; /* This is the smallest value allowed by FIPS */
441 :
442 0 : e = mpi_alloc ((32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB);
443 :
444 0 : use_e |= 1; /* make sure this is odd */
445 0 : mpi_set_ui (e, use_e);
446 :
447 0 : p = mpi_snew (pbits);
448 0 : q = mpi_snew (pbits);
449 : }
450 :
451 0 : n = mpi_new (nbits);
452 0 : d = mpi_snew (nbits);
453 0 : u = mpi_snew (nbits);
454 :
455 : /* prepare approximate minimum p and q */
456 0 : minp = mpi_new (pbits);
457 0 : mpi_set_ui (minp, 0xB504F334);
458 0 : mpi_lshift (minp, minp, pbits - 32);
459 :
460 : /* prepare minimum p and q difference */
461 0 : diff = mpi_new (pbits);
462 0 : mindiff = mpi_new (pbits - 99);
463 0 : mpi_set_ui (mindiff, 1);
464 0 : mpi_lshift (mindiff, mindiff, pbits - 100);
465 :
466 0 : p1 = mpi_snew (pbits);
467 0 : q1 = mpi_snew (pbits);
468 0 : g = mpi_snew (pbits);
469 :
470 : retry:
471 : /* generate p and q */
472 0 : for (i = 0; i < 5 * pbits; i++)
473 : {
474 : ploop:
475 0 : if (!testparms)
476 : {
477 0 : _gcry_mpi_randomize (p, pbits, random_level);
478 : }
479 0 : if (mpi_cmp (p, minp) < 0)
480 : {
481 0 : if (testparms)
482 0 : goto err;
483 0 : goto ploop;
484 : }
485 :
486 0 : mpi_sub_ui (p1, p, 1);
487 0 : if (mpi_gcd (g, p1, e))
488 : {
489 0 : if (_gcry_fips186_4_prime_check (p, pbits) != GPG_ERR_NO_ERROR)
490 : {
491 : /* not a prime */
492 0 : if (testparms)
493 0 : goto err;
494 : }
495 : else
496 0 : break;
497 : }
498 0 : else if (testparms)
499 0 : goto err;
500 : }
501 0 : if (i >= 5 * pbits)
502 0 : goto err;
503 :
504 0 : for (i = 0; i < 5 * pbits; i++)
505 : {
506 : qloop:
507 0 : if (!testparms)
508 : {
509 0 : _gcry_mpi_randomize (q, pbits, random_level);
510 : }
511 0 : if (mpi_cmp (q, minp) < 0)
512 : {
513 0 : if (testparms)
514 0 : goto err;
515 0 : goto qloop;
516 : }
517 0 : if (mpi_cmp (p, q) > 0)
518 : {
519 0 : pqswitch = 1;
520 0 : mpi_sub (diff, p, q);
521 : }
522 : else
523 : {
524 0 : pqswitch = 0;
525 0 : mpi_sub (diff, q, p);
526 : }
527 0 : if (mpi_cmp (diff, mindiff) < 0)
528 : {
529 0 : if (testparms)
530 0 : goto err;
531 0 : goto qloop;
532 : }
533 :
534 0 : mpi_sub_ui (q1, q, 1);
535 0 : if (mpi_gcd (g, q1, e))
536 : {
537 0 : if (_gcry_fips186_4_prime_check (q, pbits) != GPG_ERR_NO_ERROR)
538 : {
539 : /* not a prime */
540 0 : if (testparms)
541 0 : goto err;
542 : }
543 : else
544 0 : break;
545 : }
546 0 : else if (testparms)
547 0 : goto err;
548 : }
549 0 : if (i >= 5 * pbits)
550 0 : goto err;
551 :
552 0 : if (testparms)
553 : {
554 0 : mpi_clear (p);
555 0 : mpi_clear (q);
556 : }
557 : else
558 : {
559 : gcry_mpi_t f;
560 :
561 0 : if (pqswitch)
562 : {
563 : gcry_mpi_t tmp;
564 :
565 0 : tmp = p;
566 0 : p = q;
567 0 : q = tmp;
568 : }
569 :
570 0 : f = mpi_snew (nbits);
571 :
572 : /* calculate the modulus */
573 0 : mpi_mul (n, p, q);
574 :
575 : /* calculate the secret key d = e^1 mod phi */
576 0 : mpi_gcd (g, p1, q1);
577 0 : mpi_fdiv_q (f, p1, g);
578 0 : mpi_mul (f, f, q1);
579 :
580 0 : mpi_invm (d, e, f);
581 :
582 0 : _gcry_mpi_release (f);
583 :
584 0 : if (mpi_get_nbits (d) < pbits)
585 0 : goto retry;
586 :
587 : /* calculate the inverse of p and q (used for chinese remainder theorem)*/
588 0 : mpi_invm (u, p, q );
589 : }
590 :
591 0 : ec = 0;
592 :
593 0 : if (DBG_CIPHER)
594 : {
595 0 : log_mpidump(" p= ", p );
596 0 : log_mpidump(" q= ", q );
597 0 : log_mpidump(" n= ", n );
598 0 : log_mpidump(" e= ", e );
599 0 : log_mpidump(" d= ", d );
600 0 : log_mpidump(" u= ", u );
601 : }
602 :
603 : err:
604 :
605 0 : _gcry_mpi_release (p1);
606 0 : _gcry_mpi_release (q1);
607 0 : _gcry_mpi_release (g);
608 0 : _gcry_mpi_release (minp);
609 0 : _gcry_mpi_release (mindiff);
610 0 : _gcry_mpi_release (diff);
611 :
612 0 : sk->n = n;
613 0 : sk->e = e;
614 0 : sk->p = p;
615 0 : sk->q = q;
616 0 : sk->d = d;
617 0 : sk->u = u;
618 :
619 : /* Now we can test our keys. */
620 0 : if (ec || (!testparms && test_keys (sk, nbits - 64)))
621 : {
622 0 : _gcry_mpi_release (sk->n); sk->n = NULL;
623 0 : _gcry_mpi_release (sk->e); sk->e = NULL;
624 0 : _gcry_mpi_release (sk->p); sk->p = NULL;
625 0 : _gcry_mpi_release (sk->q); sk->q = NULL;
626 0 : _gcry_mpi_release (sk->d); sk->d = NULL;
627 0 : _gcry_mpi_release (sk->u); sk->u = NULL;
628 0 : if (!ec)
629 : {
630 0 : fips_signal_error ("self-test after key generation failed");
631 0 : return GPG_ERR_SELFTEST_FAILED;
632 : }
633 : }
634 :
635 0 : return ec;
636 : }
637 :
638 :
639 : /* Helper for generate_x931. */
640 : static gcry_mpi_t
641 4 : gen_x931_parm_xp (unsigned int nbits)
642 : {
643 : gcry_mpi_t xp;
644 :
645 4 : xp = mpi_snew (nbits);
646 4 : _gcry_mpi_randomize (xp, nbits, GCRY_VERY_STRONG_RANDOM);
647 :
648 : /* The requirement for Xp is:
649 :
650 : sqrt{2}*2^{nbits-1} <= xp <= 2^{nbits} - 1
651 :
652 : We set the two high order bits to 1 to satisfy the lower bound.
653 : By using mpi_set_highbit we make sure that the upper bound is
654 : satisfied as well. */
655 4 : mpi_set_highbit (xp, nbits-1);
656 4 : mpi_set_bit (xp, nbits-2);
657 4 : gcry_assert ( mpi_get_nbits (xp) == nbits );
658 :
659 4 : return xp;
660 : }
661 :
662 :
663 : /* Helper for generate_x931. */
664 : static gcry_mpi_t
665 8 : gen_x931_parm_xi (void)
666 : {
667 : gcry_mpi_t xi;
668 :
669 8 : xi = mpi_snew (101);
670 8 : _gcry_mpi_randomize (xi, 101, GCRY_VERY_STRONG_RANDOM);
671 8 : mpi_set_highbit (xi, 100);
672 8 : gcry_assert ( mpi_get_nbits (xi) == 101 );
673 :
674 8 : return xi;
675 : }
676 :
677 :
678 :
679 : /* Variant of the standard key generation code using the algorithm
680 : from X9.31. Using this algorithm has the advantage that the
681 : generation can be made deterministic which is required for CAVS
682 : testing. */
683 : static gpg_err_code_t
684 6 : generate_x931 (RSA_secret_key *sk, unsigned int nbits, unsigned long e_value,
685 : gcry_sexp_t deriveparms, int *swapped)
686 : {
687 : gcry_mpi_t p, q; /* The two primes. */
688 : gcry_mpi_t e; /* The public exponent. */
689 : gcry_mpi_t n; /* The public key. */
690 : gcry_mpi_t d; /* The private key */
691 : gcry_mpi_t u; /* The inverse of p and q. */
692 : gcry_mpi_t pm1; /* p - 1 */
693 : gcry_mpi_t qm1; /* q - 1 */
694 : gcry_mpi_t phi; /* Euler totient. */
695 : gcry_mpi_t f, g; /* Helper. */
696 :
697 6 : *swapped = 0;
698 :
699 6 : if (e_value == 1) /* Alias for a secure value. */
700 0 : e_value = 65537;
701 :
702 : /* Point 1 of section 4.1: k = 1024 + 256s with S >= 0 */
703 6 : if (nbits < 1024 || (nbits % 256))
704 0 : return GPG_ERR_INV_VALUE;
705 :
706 : /* Point 2: 2 <= bitlength(e) < 2^{k-2}
707 : Note that we do not need to check the upper bound because we use
708 : an unsigned long for E and thus there is no way for E to reach
709 : that limit. */
710 6 : if (e_value < 3)
711 0 : return GPG_ERR_INV_VALUE;
712 :
713 : /* Our implementaion requires E to be odd. */
714 6 : if (!(e_value & 1))
715 0 : return GPG_ERR_INV_VALUE;
716 :
717 : /* Point 3: e > 0 or e 0 if it is to be randomly generated.
718 : We support only a fixed E and thus there is no need for an extra test. */
719 :
720 :
721 : /* Compute or extract the derive parameters. */
722 : {
723 6 : gcry_mpi_t xp1 = NULL;
724 6 : gcry_mpi_t xp2 = NULL;
725 6 : gcry_mpi_t xp = NULL;
726 6 : gcry_mpi_t xq1 = NULL;
727 6 : gcry_mpi_t xq2 = NULL;
728 6 : gcry_mpi_t xq = NULL;
729 : gcry_mpi_t tmpval;
730 :
731 6 : if (!deriveparms)
732 : {
733 : /* Not given: Generate them. */
734 2 : xp = gen_x931_parm_xp (nbits/2);
735 : /* Make sure that |xp - xq| > 2^{nbits - 100} holds. */
736 2 : tmpval = mpi_snew (nbits/2);
737 : do
738 : {
739 2 : _gcry_mpi_release (xq);
740 2 : xq = gen_x931_parm_xp (nbits/2);
741 2 : mpi_sub (tmpval, xp, xq);
742 : }
743 2 : while (mpi_get_nbits (tmpval) <= (nbits/2 - 100));
744 2 : _gcry_mpi_release (tmpval);
745 :
746 2 : xp1 = gen_x931_parm_xi ();
747 2 : xp2 = gen_x931_parm_xi ();
748 2 : xq1 = gen_x931_parm_xi ();
749 2 : xq2 = gen_x931_parm_xi ();
750 :
751 : }
752 : else
753 : {
754 : /* Parameters to derive the key are given. */
755 : /* Note that we explicitly need to setup the values of tbl
756 : because some compilers (e.g. OpenWatcom, IRIX) don't allow
757 : to initialize a structure with automatic variables. */
758 4 : struct { const char *name; gcry_mpi_t *value; } tbl[] = {
759 : { "Xp1" },
760 : { "Xp2" },
761 : { "Xp" },
762 : { "Xq1" },
763 : { "Xq2" },
764 : { "Xq" },
765 : { NULL }
766 : };
767 : int idx;
768 : gcry_sexp_t oneparm;
769 :
770 4 : tbl[0].value = &xp1;
771 4 : tbl[1].value = &xp2;
772 4 : tbl[2].value = &xp;
773 4 : tbl[3].value = &xq1;
774 4 : tbl[4].value = &xq2;
775 4 : tbl[5].value = &xq;
776 :
777 28 : for (idx=0; tbl[idx].name; idx++)
778 : {
779 24 : oneparm = sexp_find_token (deriveparms, tbl[idx].name, 0);
780 24 : if (oneparm)
781 : {
782 24 : *tbl[idx].value = sexp_nth_mpi (oneparm, 1, GCRYMPI_FMT_USG);
783 24 : sexp_release (oneparm);
784 : }
785 : }
786 28 : for (idx=0; tbl[idx].name; idx++)
787 24 : if (!*tbl[idx].value)
788 0 : break;
789 4 : if (tbl[idx].name)
790 : {
791 : /* At least one parameter is missing. */
792 0 : for (idx=0; tbl[idx].name; idx++)
793 0 : _gcry_mpi_release (*tbl[idx].value);
794 0 : return GPG_ERR_MISSING_VALUE;
795 : }
796 : }
797 :
798 6 : e = mpi_alloc_set_ui (e_value);
799 :
800 : /* Find two prime numbers. */
801 6 : p = _gcry_derive_x931_prime (xp, xp1, xp2, e, NULL, NULL);
802 6 : q = _gcry_derive_x931_prime (xq, xq1, xq2, e, NULL, NULL);
803 6 : _gcry_mpi_release (xp); xp = NULL;
804 6 : _gcry_mpi_release (xp1); xp1 = NULL;
805 6 : _gcry_mpi_release (xp2); xp2 = NULL;
806 6 : _gcry_mpi_release (xq); xq = NULL;
807 6 : _gcry_mpi_release (xq1); xq1 = NULL;
808 6 : _gcry_mpi_release (xq2); xq2 = NULL;
809 6 : if (!p || !q)
810 : {
811 0 : _gcry_mpi_release (p);
812 0 : _gcry_mpi_release (q);
813 0 : _gcry_mpi_release (e);
814 0 : return GPG_ERR_NO_PRIME;
815 : }
816 : }
817 :
818 :
819 : /* Compute the public modulus. We make sure that p is smaller than
820 : q to allow the use of the CRT. */
821 6 : if (mpi_cmp (p, q) > 0 )
822 : {
823 3 : mpi_swap (p, q);
824 3 : *swapped = 1;
825 : }
826 6 : n = mpi_new (nbits);
827 6 : mpi_mul (n, p, q);
828 :
829 : /* Compute the Euler totient: phi = (p-1)(q-1) */
830 6 : pm1 = mpi_snew (nbits/2);
831 6 : qm1 = mpi_snew (nbits/2);
832 6 : phi = mpi_snew (nbits);
833 6 : mpi_sub_ui (pm1, p, 1);
834 6 : mpi_sub_ui (qm1, q, 1);
835 6 : mpi_mul (phi, pm1, qm1);
836 :
837 6 : g = mpi_snew (nbits);
838 6 : gcry_assert (mpi_gcd (g, e, phi));
839 :
840 : /* Compute: f = lcm(p-1,q-1) = phi / gcd(p-1,q-1) */
841 6 : mpi_gcd (g, pm1, qm1);
842 6 : f = pm1; pm1 = NULL;
843 6 : _gcry_mpi_release (qm1); qm1 = NULL;
844 6 : mpi_fdiv_q (f, phi, g);
845 6 : _gcry_mpi_release (phi); phi = NULL;
846 6 : d = g; g = NULL;
847 : /* Compute the secret key: d = e^{-1} mod lcm(p-1,q-1) */
848 6 : mpi_invm (d, e, f);
849 :
850 : /* Compute the inverse of p and q. */
851 6 : u = f; f = NULL;
852 6 : mpi_invm (u, p, q );
853 :
854 6 : if( DBG_CIPHER )
855 : {
856 0 : if (*swapped)
857 0 : log_debug ("p and q are swapped\n");
858 0 : log_mpidump(" p", p );
859 0 : log_mpidump(" q", q );
860 0 : log_mpidump(" n", n );
861 0 : log_mpidump(" e", e );
862 0 : log_mpidump(" d", d );
863 0 : log_mpidump(" u", u );
864 : }
865 :
866 :
867 6 : sk->n = n;
868 6 : sk->e = e;
869 6 : sk->p = p;
870 6 : sk->q = q;
871 6 : sk->d = d;
872 6 : sk->u = u;
873 :
874 : /* Now we can test our keys. */
875 6 : if (test_keys (sk, nbits - 64))
876 : {
877 0 : _gcry_mpi_release (sk->n); sk->n = NULL;
878 0 : _gcry_mpi_release (sk->e); sk->e = NULL;
879 0 : _gcry_mpi_release (sk->p); sk->p = NULL;
880 0 : _gcry_mpi_release (sk->q); sk->q = NULL;
881 0 : _gcry_mpi_release (sk->d); sk->d = NULL;
882 0 : _gcry_mpi_release (sk->u); sk->u = NULL;
883 0 : fips_signal_error ("self-test after key generation failed");
884 0 : return GPG_ERR_SELFTEST_FAILED;
885 : }
886 :
887 6 : return 0;
888 : }
889 :
890 :
891 : /****************
892 : * Test whether the secret key is valid.
893 : * Returns: true if this is a valid key.
894 : */
895 : static int
896 8 : check_secret_key( RSA_secret_key *sk )
897 : {
898 : int rc;
899 8 : gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(sk->p)*2 );
900 :
901 8 : mpi_mul(temp, sk->p, sk->q );
902 8 : rc = mpi_cmp( temp, sk->n );
903 8 : mpi_free(temp);
904 8 : return !rc;
905 : }
906 :
907 :
908 :
909 : /****************
910 : * Public key operation. Encrypt INPUT with PKEY and put result into OUTPUT.
911 : *
912 : * c = m^e mod n
913 : *
914 : * Where c is OUTPUT, m is INPUT and e,n are elements of PKEY.
915 : */
916 : static void
917 2145 : public(gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *pkey )
918 : {
919 2145 : if( output == input ) /* powm doesn't like output and input the same */
920 : {
921 0 : gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs(input)*2 );
922 0 : mpi_powm( x, input, pkey->e, pkey->n );
923 0 : mpi_set(output, x);
924 0 : mpi_free(x);
925 : }
926 : else
927 2145 : mpi_powm( output, input, pkey->e, pkey->n );
928 2145 : }
929 :
930 : #if 0
931 : static void
932 : stronger_key_check ( RSA_secret_key *skey )
933 : {
934 : gcry_mpi_t t = mpi_alloc_secure ( 0 );
935 : gcry_mpi_t t1 = mpi_alloc_secure ( 0 );
936 : gcry_mpi_t t2 = mpi_alloc_secure ( 0 );
937 : gcry_mpi_t phi = mpi_alloc_secure ( 0 );
938 :
939 : /* check that n == p * q */
940 : mpi_mul( t, skey->p, skey->q);
941 : if (mpi_cmp( t, skey->n) )
942 : log_info ( "RSA Oops: n != p * q\n" );
943 :
944 : /* check that p is less than q */
945 : if( mpi_cmp( skey->p, skey->q ) > 0 )
946 : {
947 : log_info ("RSA Oops: p >= q - fixed\n");
948 : _gcry_mpi_swap ( skey->p, skey->q);
949 : }
950 :
951 : /* check that e divides neither p-1 nor q-1 */
952 : mpi_sub_ui(t, skey->p, 1 );
953 : mpi_fdiv_r(t, t, skey->e );
954 : if ( !mpi_cmp_ui( t, 0) )
955 : log_info ( "RSA Oops: e divides p-1\n" );
956 : mpi_sub_ui(t, skey->q, 1 );
957 : mpi_fdiv_r(t, t, skey->e );
958 : if ( !mpi_cmp_ui( t, 0) )
959 : log_info ( "RSA Oops: e divides q-1\n" );
960 :
961 : /* check that d is correct */
962 : mpi_sub_ui( t1, skey->p, 1 );
963 : mpi_sub_ui( t2, skey->q, 1 );
964 : mpi_mul( phi, t1, t2 );
965 : gcry_mpi_gcd(t, t1, t2);
966 : mpi_fdiv_q(t, phi, t);
967 : mpi_invm(t, skey->e, t );
968 : if ( mpi_cmp(t, skey->d ) )
969 : {
970 : log_info ( "RSA Oops: d is wrong - fixed\n");
971 : mpi_set (skey->d, t);
972 : log_printmpi (" fixed d", skey->d);
973 : }
974 :
975 : /* check for correctness of u */
976 : mpi_invm(t, skey->p, skey->q );
977 : if ( mpi_cmp(t, skey->u ) )
978 : {
979 : log_info ( "RSA Oops: u is wrong - fixed\n");
980 : mpi_set (skey->u, t);
981 : log_printmpi (" fixed u", skey->u);
982 : }
983 :
984 : log_info ( "RSA secret key check finished\n");
985 :
986 : mpi_free (t);
987 : mpi_free (t1);
988 : mpi_free (t2);
989 : mpi_free (phi);
990 : }
991 : #endif
992 :
993 :
994 :
995 : /****************
996 : * Secret key operation. Encrypt INPUT with SKEY and put result into OUTPUT.
997 : *
998 : * m = c^d mod n
999 : *
1000 : * Or faster:
1001 : *
1002 : * m1 = c ^ (d mod (p-1)) mod p
1003 : * m2 = c ^ (d mod (q-1)) mod q
1004 : * h = u * (m2 - m1) mod q
1005 : * m = m1 + h * p
1006 : *
1007 : * Where m is OUTPUT, c is INPUT and d,n,p,q,u are elements of SKEY.
1008 : */
1009 : static void
1010 1318 : secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey )
1011 : {
1012 : /* Remove superfluous leading zeroes from INPUT. */
1013 1318 : mpi_normalize (input);
1014 :
1015 1318 : if (!skey->p || !skey->q || !skey->u)
1016 : {
1017 728 : mpi_powm (output, input, skey->d, skey->n);
1018 : }
1019 : else
1020 : {
1021 590 : gcry_mpi_t m1 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
1022 590 : gcry_mpi_t m2 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
1023 590 : gcry_mpi_t h = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
1024 :
1025 : /* m1 = c ^ (d mod (p-1)) mod p */
1026 590 : mpi_sub_ui( h, skey->p, 1 );
1027 590 : mpi_fdiv_r( h, skey->d, h );
1028 590 : mpi_powm( m1, input, h, skey->p );
1029 : /* m2 = c ^ (d mod (q-1)) mod q */
1030 590 : mpi_sub_ui( h, skey->q, 1 );
1031 590 : mpi_fdiv_r( h, skey->d, h );
1032 590 : mpi_powm( m2, input, h, skey->q );
1033 : /* h = u * ( m2 - m1 ) mod q */
1034 590 : mpi_sub( h, m2, m1 );
1035 590 : if ( mpi_has_sign ( h ) )
1036 265 : mpi_add ( h, h, skey->q );
1037 590 : mpi_mulm( h, skey->u, h, skey->q );
1038 : /* m = m1 + h * p */
1039 590 : mpi_mul ( h, h, skey->p );
1040 590 : mpi_add ( output, m1, h );
1041 :
1042 590 : mpi_free ( h );
1043 590 : mpi_free ( m1 );
1044 590 : mpi_free ( m2 );
1045 : }
1046 1318 : }
1047 :
1048 : static void
1049 1240 : secret_blinded (gcry_mpi_t output, gcry_mpi_t input,
1050 : RSA_secret_key *sk, unsigned int nbits)
1051 : {
1052 : gcry_mpi_t r; /* Random number needed for blinding. */
1053 : gcry_mpi_t ri; /* Modular multiplicative inverse of r. */
1054 : gcry_mpi_t bldata; /* Blinded data to decrypt. */
1055 :
1056 : /* First, we need a random number r between 0 and n - 1, which is
1057 : * relatively prime to n (i.e. it is neither p nor q). The random
1058 : * number needs to be only unpredictable, thus we employ the
1059 : * gcry_create_nonce function by using GCRY_WEAK_RANDOM with
1060 : * gcry_mpi_randomize. */
1061 1240 : r = mpi_snew (nbits);
1062 1240 : ri = mpi_snew (nbits);
1063 1240 : bldata = mpi_snew (nbits);
1064 :
1065 : do
1066 : {
1067 1240 : _gcry_mpi_randomize (r, nbits, GCRY_WEAK_RANDOM);
1068 1240 : mpi_mod (r, r, sk->n);
1069 : }
1070 1240 : while (!mpi_invm (ri, r, sk->n));
1071 :
1072 : /* Do blinding. We calculate: y = (x * r^e) mod n, where r is the
1073 : * random number, e is the public exponent, x is the non-blinded
1074 : * input data and n is the RSA modulus. */
1075 1240 : mpi_powm (bldata, r, sk->e, sk->n);
1076 1240 : mpi_mulm (bldata, bldata, input, sk->n);
1077 :
1078 : /* Perform decryption. */
1079 1240 : secret (output, bldata, sk);
1080 1240 : _gcry_mpi_release (bldata);
1081 :
1082 : /* Undo blinding. Here we calculate: y = (x * r^-1) mod n, where x
1083 : * is the blinded decrypted data, ri is the modular multiplicative
1084 : * inverse of r and n is the RSA modulus. */
1085 1240 : mpi_mulm (output, output, ri, sk->n);
1086 :
1087 1240 : _gcry_mpi_release (r);
1088 1240 : _gcry_mpi_release (ri);
1089 1240 : }
1090 :
1091 : /*********************************************
1092 : ************** interface ******************
1093 : *********************************************/
1094 :
1095 : static gcry_err_code_t
1096 39 : rsa_generate (const gcry_sexp_t genparms, gcry_sexp_t *r_skey)
1097 : {
1098 : gpg_err_code_t ec;
1099 : unsigned int nbits;
1100 : unsigned long evalue;
1101 : RSA_secret_key sk;
1102 : gcry_sexp_t deriveparms;
1103 39 : int flags = 0;
1104 : gcry_sexp_t l1;
1105 39 : gcry_sexp_t swap_info = NULL;
1106 :
1107 39 : memset (&sk, 0, sizeof sk);
1108 :
1109 39 : ec = _gcry_pk_util_get_nbits (genparms, &nbits);
1110 39 : if (ec)
1111 0 : return ec;
1112 :
1113 39 : ec = _gcry_pk_util_get_rsa_use_e (genparms, &evalue);
1114 39 : if (ec)
1115 0 : return ec;
1116 :
1117 : /* Parse the optional flags list. */
1118 39 : l1 = sexp_find_token (genparms, "flags", 0);
1119 39 : if (l1)
1120 : {
1121 0 : ec = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);
1122 0 : sexp_release (l1);
1123 0 : if (ec)
1124 0 : return ec;
1125 : }
1126 :
1127 39 : deriveparms = (genparms?
1128 39 : sexp_find_token (genparms, "derive-parms", 0) : NULL);
1129 39 : if (!deriveparms)
1130 : {
1131 : /* Parse the optional "use-x931" flag. */
1132 35 : l1 = sexp_find_token (genparms, "use-x931", 0);
1133 35 : if (l1)
1134 : {
1135 2 : flags |= PUBKEY_FLAG_USE_X931;
1136 2 : sexp_release (l1);
1137 : }
1138 : }
1139 :
1140 39 : if (deriveparms || (flags & PUBKEY_FLAG_USE_X931))
1141 6 : {
1142 : int swapped;
1143 6 : ec = generate_x931 (&sk, nbits, evalue, deriveparms, &swapped);
1144 6 : sexp_release (deriveparms);
1145 6 : if (!ec && swapped)
1146 3 : ec = sexp_new (&swap_info, "(misc-key-info(p-q-swapped))", 0, 1);
1147 : }
1148 : else
1149 : {
1150 : /* Parse the optional "transient-key" flag. */
1151 33 : if (!(flags & PUBKEY_FLAG_TRANSIENT_KEY))
1152 : {
1153 33 : l1 = sexp_find_token (genparms, "transient-key", 0);
1154 33 : if (l1)
1155 : {
1156 26 : flags |= PUBKEY_FLAG_TRANSIENT_KEY;
1157 26 : sexp_release (l1);
1158 : }
1159 : }
1160 33 : deriveparms = (genparms? sexp_find_token (genparms, "test-parms", 0)
1161 33 : /**/ : NULL);
1162 :
1163 : /* Generate. */
1164 33 : if (deriveparms || fips_mode())
1165 : {
1166 0 : ec = generate_fips (&sk, nbits, evalue, deriveparms,
1167 0 : !!(flags & PUBKEY_FLAG_TRANSIENT_KEY));
1168 : }
1169 : else
1170 : {
1171 33 : ec = generate_std (&sk, nbits, evalue,
1172 33 : !!(flags & PUBKEY_FLAG_TRANSIENT_KEY));
1173 : }
1174 33 : sexp_release (deriveparms);
1175 : }
1176 :
1177 39 : if (!ec)
1178 : {
1179 39 : ec = sexp_build (r_skey, NULL,
1180 : "(key-data"
1181 : " (public-key"
1182 : " (rsa(n%m)(e%m)))"
1183 : " (private-key"
1184 : " (rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))"
1185 : " %S)",
1186 : sk.n, sk.e,
1187 : sk.n, sk.e, sk.d, sk.p, sk.q, sk.u,
1188 : swap_info);
1189 : }
1190 :
1191 39 : mpi_free (sk.n);
1192 39 : mpi_free (sk.e);
1193 39 : mpi_free (sk.p);
1194 39 : mpi_free (sk.q);
1195 39 : mpi_free (sk.d);
1196 39 : mpi_free (sk.u);
1197 39 : sexp_release (swap_info);
1198 :
1199 39 : return ec;
1200 : }
1201 :
1202 :
1203 : static gcry_err_code_t
1204 12 : rsa_check_secret_key (gcry_sexp_t keyparms)
1205 : {
1206 : gcry_err_code_t rc;
1207 12 : RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL};
1208 :
1209 : /* To check the key we need the optional parameters. */
1210 12 : rc = sexp_extract_param (keyparms, NULL, "nedpqu",
1211 : &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u,
1212 : NULL);
1213 12 : if (rc)
1214 4 : goto leave;
1215 :
1216 8 : if (!check_secret_key (&sk))
1217 0 : rc = GPG_ERR_BAD_SECKEY;
1218 :
1219 : leave:
1220 12 : _gcry_mpi_release (sk.n);
1221 12 : _gcry_mpi_release (sk.e);
1222 12 : _gcry_mpi_release (sk.d);
1223 12 : _gcry_mpi_release (sk.p);
1224 12 : _gcry_mpi_release (sk.q);
1225 12 : _gcry_mpi_release (sk.u);
1226 12 : if (DBG_CIPHER)
1227 0 : log_debug ("rsa_testkey => %s\n", gpg_strerror (rc));
1228 12 : return rc;
1229 : }
1230 :
1231 :
1232 : static gcry_err_code_t
1233 718 : rsa_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1234 : {
1235 : gcry_err_code_t rc;
1236 : struct pk_encoding_ctx ctx;
1237 718 : gcry_mpi_t data = NULL;
1238 718 : RSA_public_key pk = {NULL, NULL};
1239 718 : gcry_mpi_t ciph = NULL;
1240 :
1241 718 : _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT,
1242 : rsa_get_nbits (keyparms));
1243 :
1244 : /* Extract the data. */
1245 718 : rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
1246 718 : if (rc)
1247 72 : goto leave;
1248 646 : if (DBG_CIPHER)
1249 0 : log_mpidump ("rsa_encrypt data", data);
1250 646 : if (!data || mpi_is_opaque (data))
1251 : {
1252 0 : rc = GPG_ERR_INV_DATA;
1253 0 : goto leave;
1254 : }
1255 :
1256 : /* Extract the key. */
1257 646 : rc = sexp_extract_param (keyparms, NULL, "ne", &pk.n, &pk.e, NULL);
1258 646 : if (rc)
1259 0 : goto leave;
1260 646 : if (DBG_CIPHER)
1261 : {
1262 0 : log_mpidump ("rsa_encrypt n", pk.n);
1263 0 : log_mpidump ("rsa_encrypt e", pk.e);
1264 : }
1265 :
1266 : /* Do RSA computation and build result. */
1267 646 : ciph = mpi_new (0);
1268 646 : public (ciph, data, &pk);
1269 646 : if (DBG_CIPHER)
1270 0 : log_mpidump ("rsa_encrypt res", ciph);
1271 646 : if ((ctx.flags & PUBKEY_FLAG_FIXEDLEN))
1272 : {
1273 : /* We need to make sure to return the correct length to avoid
1274 : problems with missing leading zeroes. */
1275 : unsigned char *em;
1276 528 : size_t emlen = (mpi_get_nbits (pk.n)+7)/8;
1277 :
1278 528 : rc = _gcry_mpi_to_octet_string (&em, NULL, ciph, emlen);
1279 528 : if (!rc)
1280 : {
1281 528 : rc = sexp_build (r_ciph, NULL, "(enc-val(rsa(a%b)))", (int)emlen, em);
1282 528 : xfree (em);
1283 : }
1284 : }
1285 : else
1286 118 : rc = sexp_build (r_ciph, NULL, "(enc-val(rsa(a%m)))", ciph);
1287 :
1288 : leave:
1289 718 : _gcry_mpi_release (ciph);
1290 718 : _gcry_mpi_release (pk.n);
1291 718 : _gcry_mpi_release (pk.e);
1292 718 : _gcry_mpi_release (data);
1293 718 : _gcry_pk_util_free_encoding_ctx (&ctx);
1294 718 : if (DBG_CIPHER)
1295 0 : log_debug ("rsa_encrypt => %s\n", gpg_strerror (rc));
1296 718 : return rc;
1297 : }
1298 :
1299 :
1300 : static gcry_err_code_t
1301 646 : rsa_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1302 :
1303 : {
1304 : gpg_err_code_t rc;
1305 : struct pk_encoding_ctx ctx;
1306 646 : gcry_sexp_t l1 = NULL;
1307 646 : gcry_mpi_t data = NULL;
1308 646 : RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL};
1309 646 : gcry_mpi_t plain = NULL;
1310 646 : unsigned char *unpad = NULL;
1311 646 : size_t unpadlen = 0;
1312 :
1313 646 : _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT,
1314 : rsa_get_nbits (keyparms));
1315 :
1316 : /* Extract the data. */
1317 646 : rc = _gcry_pk_util_preparse_encval (s_data, rsa_names, &l1, &ctx);
1318 646 : if (rc)
1319 0 : goto leave;
1320 646 : rc = sexp_extract_param (l1, NULL, "a", &data, NULL);
1321 646 : if (rc)
1322 0 : goto leave;
1323 646 : if (DBG_CIPHER)
1324 0 : log_printmpi ("rsa_decrypt data", data);
1325 646 : if (mpi_is_opaque (data))
1326 : {
1327 0 : rc = GPG_ERR_INV_DATA;
1328 0 : goto leave;
1329 : }
1330 :
1331 : /* Extract the key. */
1332 646 : rc = sexp_extract_param (keyparms, NULL, "nedp?q?u?",
1333 : &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u,
1334 : NULL);
1335 646 : if (rc)
1336 0 : goto leave;
1337 646 : if (DBG_CIPHER)
1338 : {
1339 0 : log_printmpi ("rsa_decrypt n", sk.n);
1340 0 : log_printmpi ("rsa_decrypt e", sk.e);
1341 0 : if (!fips_mode ())
1342 : {
1343 0 : log_printmpi ("rsa_decrypt d", sk.d);
1344 0 : log_printmpi ("rsa_decrypt p", sk.p);
1345 0 : log_printmpi ("rsa_decrypt q", sk.q);
1346 0 : log_printmpi ("rsa_decrypt u", sk.u);
1347 : }
1348 : }
1349 :
1350 : /* Better make sure that there are no superfluous leading zeroes in
1351 : the input and it has not been "padded" using multiples of N.
1352 : This mitigates side-channel attacks (CVE-2013-4576). */
1353 646 : mpi_normalize (data);
1354 646 : mpi_fdiv_r (data, data, sk.n);
1355 :
1356 : /* Allocate MPI for the plaintext. */
1357 646 : plain = mpi_snew (ctx.nbits);
1358 :
1359 : /* We use blinding by default to mitigate timing attacks which can
1360 : be practically mounted over the network as shown by Brumley and
1361 : Boney in 2003. */
1362 646 : if ((ctx.flags & PUBKEY_FLAG_NO_BLINDING))
1363 0 : secret (plain, data, &sk);
1364 : else
1365 646 : secret_blinded (plain, data, &sk, ctx.nbits);
1366 :
1367 646 : if (DBG_CIPHER)
1368 0 : log_printmpi ("rsa_decrypt res", plain);
1369 :
1370 : /* Reverse the encoding and build the s-expression. */
1371 646 : switch (ctx.encoding)
1372 : {
1373 : case PUBKEY_ENC_PKCS1:
1374 348 : rc = _gcry_rsa_pkcs1_decode_for_enc (&unpad, &unpadlen, ctx.nbits, plain);
1375 348 : mpi_free (plain);
1376 348 : plain = NULL;
1377 348 : if (!rc)
1378 324 : rc = sexp_build (r_plain, NULL, "(value %b)", (int)unpadlen, unpad);
1379 348 : break;
1380 :
1381 : case PUBKEY_ENC_OAEP:
1382 360 : rc = _gcry_rsa_oaep_decode (&unpad, &unpadlen,
1383 : ctx.nbits, ctx.hash_algo,
1384 180 : plain, ctx.label, ctx.labellen);
1385 180 : mpi_free (plain);
1386 180 : plain = NULL;
1387 180 : if (!rc)
1388 156 : rc = sexp_build (r_plain, NULL, "(value %b)", (int)unpadlen, unpad);
1389 180 : break;
1390 :
1391 : default:
1392 : /* Raw format. For backward compatibility we need to assume a
1393 : signed mpi by using the sexp format string "%m". */
1394 118 : rc = sexp_build (r_plain, NULL,
1395 118 : (ctx.flags & PUBKEY_FLAG_LEGACYRESULT)
1396 : ? "%m":"(value %m)", plain);
1397 118 : break;
1398 : }
1399 :
1400 : leave:
1401 646 : xfree (unpad);
1402 646 : _gcry_mpi_release (plain);
1403 646 : _gcry_mpi_release (sk.n);
1404 646 : _gcry_mpi_release (sk.e);
1405 646 : _gcry_mpi_release (sk.d);
1406 646 : _gcry_mpi_release (sk.p);
1407 646 : _gcry_mpi_release (sk.q);
1408 646 : _gcry_mpi_release (sk.u);
1409 646 : _gcry_mpi_release (data);
1410 646 : sexp_release (l1);
1411 646 : _gcry_pk_util_free_encoding_ctx (&ctx);
1412 646 : if (DBG_CIPHER)
1413 0 : log_debug ("rsa_decrypt => %s\n", gpg_strerror (rc));
1414 646 : return rc;
1415 : }
1416 :
1417 :
1418 : static gcry_err_code_t
1419 738 : rsa_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1420 : {
1421 : gpg_err_code_t rc;
1422 : struct pk_encoding_ctx ctx;
1423 738 : gcry_mpi_t data = NULL;
1424 738 : RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL};
1425 : RSA_public_key pk;
1426 738 : gcry_mpi_t sig = NULL;
1427 738 : gcry_mpi_t result = NULL;
1428 :
1429 738 : _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_SIGN,
1430 : rsa_get_nbits (keyparms));
1431 :
1432 : /* Extract the data. */
1433 738 : rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
1434 738 : if (rc)
1435 144 : goto leave;
1436 594 : if (DBG_CIPHER)
1437 0 : log_printmpi ("rsa_sign data", data);
1438 594 : if (mpi_is_opaque (data))
1439 : {
1440 0 : rc = GPG_ERR_INV_DATA;
1441 0 : goto leave;
1442 : }
1443 :
1444 : /* Extract the key. */
1445 594 : rc = sexp_extract_param (keyparms, NULL, "nedp?q?u?",
1446 : &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u,
1447 : NULL);
1448 594 : if (rc)
1449 0 : goto leave;
1450 594 : if (DBG_CIPHER)
1451 : {
1452 0 : log_printmpi ("rsa_sign n", sk.n);
1453 0 : log_printmpi ("rsa_sign e", sk.e);
1454 0 : if (!fips_mode ())
1455 : {
1456 0 : log_printmpi ("rsa_sign d", sk.d);
1457 0 : log_printmpi ("rsa_sign p", sk.p);
1458 0 : log_printmpi ("rsa_sign q", sk.q);
1459 0 : log_printmpi ("rsa_sign u", sk.u);
1460 : }
1461 : }
1462 :
1463 : /* Do RSA computation. */
1464 594 : sig = mpi_new (0);
1465 594 : if ((ctx.flags & PUBKEY_FLAG_NO_BLINDING))
1466 0 : secret (sig, data, &sk);
1467 : else
1468 594 : secret_blinded (sig, data, &sk, ctx.nbits);
1469 594 : if (DBG_CIPHER)
1470 0 : log_printmpi ("rsa_sign res", sig);
1471 :
1472 : /* Check that the created signature is good. This detects a failure
1473 : of the CRT algorithm (Lenstra's attack on RSA's use of the CRT). */
1474 594 : result = mpi_new (0);
1475 594 : pk.n = sk.n;
1476 594 : pk.e = sk.e;
1477 594 : public (result, sig, &pk);
1478 594 : if (mpi_cmp (result, data))
1479 : {
1480 0 : rc = GPG_ERR_BAD_SIGNATURE;
1481 0 : goto leave;
1482 : }
1483 :
1484 : /* Convert the result. */
1485 594 : if ((ctx.flags & PUBKEY_FLAG_FIXEDLEN))
1486 : {
1487 : /* We need to make sure to return the correct length to avoid
1488 : problems with missing leading zeroes. */
1489 : unsigned char *em;
1490 482 : size_t emlen = (mpi_get_nbits (sk.n)+7)/8;
1491 :
1492 482 : rc = _gcry_mpi_to_octet_string (&em, NULL, sig, emlen);
1493 482 : if (!rc)
1494 : {
1495 482 : rc = sexp_build (r_sig, NULL, "(sig-val(rsa(s%b)))", (int)emlen, em);
1496 482 : xfree (em);
1497 : }
1498 : }
1499 : else
1500 112 : rc = sexp_build (r_sig, NULL, "(sig-val(rsa(s%M)))", sig);
1501 :
1502 :
1503 : leave:
1504 738 : _gcry_mpi_release (result);
1505 738 : _gcry_mpi_release (sig);
1506 738 : _gcry_mpi_release (sk.n);
1507 738 : _gcry_mpi_release (sk.e);
1508 738 : _gcry_mpi_release (sk.d);
1509 738 : _gcry_mpi_release (sk.p);
1510 738 : _gcry_mpi_release (sk.q);
1511 738 : _gcry_mpi_release (sk.u);
1512 738 : _gcry_mpi_release (data);
1513 738 : _gcry_pk_util_free_encoding_ctx (&ctx);
1514 738 : if (DBG_CIPHER)
1515 0 : log_debug ("rsa_sign => %s\n", gpg_strerror (rc));
1516 738 : return rc;
1517 : }
1518 :
1519 :
1520 : static gcry_err_code_t
1521 788 : rsa_verify (gcry_sexp_t s_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1522 : {
1523 : gcry_err_code_t rc;
1524 : struct pk_encoding_ctx ctx;
1525 788 : gcry_sexp_t l1 = NULL;
1526 788 : gcry_mpi_t sig = NULL;
1527 788 : gcry_mpi_t data = NULL;
1528 788 : RSA_public_key pk = { NULL, NULL };
1529 788 : gcry_mpi_t result = NULL;
1530 :
1531 788 : _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY,
1532 : rsa_get_nbits (keyparms));
1533 :
1534 : /* Extract the data. */
1535 788 : rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
1536 788 : if (rc)
1537 0 : goto leave;
1538 788 : if (DBG_CIPHER)
1539 0 : log_printmpi ("rsa_verify data", data);
1540 788 : if (mpi_is_opaque (data))
1541 : {
1542 0 : rc = GPG_ERR_INV_DATA;
1543 0 : goto leave;
1544 : }
1545 :
1546 : /* Extract the signature value. */
1547 788 : rc = _gcry_pk_util_preparse_sigval (s_sig, rsa_names, &l1, NULL);
1548 788 : if (rc)
1549 0 : goto leave;
1550 788 : rc = sexp_extract_param (l1, NULL, "s", &sig, NULL);
1551 788 : if (rc)
1552 0 : goto leave;
1553 788 : if (DBG_CIPHER)
1554 0 : log_printmpi ("rsa_verify sig", sig);
1555 :
1556 : /* Extract the key. */
1557 788 : rc = sexp_extract_param (keyparms, NULL, "ne", &pk.n, &pk.e, NULL);
1558 788 : if (rc)
1559 0 : goto leave;
1560 788 : if (DBG_CIPHER)
1561 : {
1562 0 : log_printmpi ("rsa_verify n", pk.n);
1563 0 : log_printmpi ("rsa_verify e", pk.e);
1564 : }
1565 :
1566 : /* Do RSA computation and compare. */
1567 788 : result = mpi_new (0);
1568 788 : public (result, sig, &pk);
1569 788 : if (DBG_CIPHER)
1570 0 : log_printmpi ("rsa_verify cmp", result);
1571 788 : if (ctx.verify_cmp)
1572 108 : rc = ctx.verify_cmp (&ctx, result);
1573 : else
1574 680 : rc = mpi_cmp (result, data) ? GPG_ERR_BAD_SIGNATURE : 0;
1575 :
1576 : leave:
1577 788 : _gcry_mpi_release (result);
1578 788 : _gcry_mpi_release (pk.n);
1579 788 : _gcry_mpi_release (pk.e);
1580 788 : _gcry_mpi_release (data);
1581 788 : _gcry_mpi_release (sig);
1582 788 : sexp_release (l1);
1583 788 : _gcry_pk_util_free_encoding_ctx (&ctx);
1584 788 : if (DBG_CIPHER)
1585 0 : log_debug ("rsa_verify => %s\n", rc?gpg_strerror (rc):"Good");
1586 788 : return rc;
1587 : }
1588 :
1589 :
1590 :
1591 : /* Return the number of bits for the key described by PARMS. On error
1592 : * 0 is returned. The format of PARMS starts with the algorithm name;
1593 : * for example:
1594 : *
1595 : * (rsa
1596 : * (n <mpi>)
1597 : * (e <mpi>))
1598 : *
1599 : * More parameters may be given but we only need N here.
1600 : */
1601 : static unsigned int
1602 2890 : rsa_get_nbits (gcry_sexp_t parms)
1603 : {
1604 : gcry_sexp_t l1;
1605 : gcry_mpi_t n;
1606 : unsigned int nbits;
1607 :
1608 2890 : l1 = sexp_find_token (parms, "n", 1);
1609 2890 : if (!l1)
1610 0 : return 0; /* Parameter N not found. */
1611 :
1612 2890 : n = sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG);
1613 2890 : sexp_release (l1);
1614 2890 : nbits = n? mpi_get_nbits (n) : 0;
1615 2890 : _gcry_mpi_release (n);
1616 2890 : return nbits;
1617 : }
1618 :
1619 :
1620 : /* Compute a keygrip. MD is the hash context which we are going to
1621 : update. KEYPARAM is an S-expression with the key parameters, this
1622 : is usually a public key but may also be a secret key. An example
1623 : of such an S-expression is:
1624 :
1625 : (rsa
1626 : (n #00B...#)
1627 : (e #010001#))
1628 :
1629 : PKCS-15 says that for RSA only the modulus should be hashed -
1630 : however, it is not clear whether this is meant to use the raw bytes
1631 : (assuming this is an unsigned integer) or whether the DER required
1632 : 0 should be prefixed. We hash the raw bytes. */
1633 : static gpg_err_code_t
1634 1 : compute_keygrip (gcry_md_hd_t md, gcry_sexp_t keyparam)
1635 : {
1636 : gcry_sexp_t l1;
1637 : const char *data;
1638 : size_t datalen;
1639 :
1640 1 : l1 = sexp_find_token (keyparam, "n", 1);
1641 1 : if (!l1)
1642 0 : return GPG_ERR_NO_OBJ;
1643 :
1644 1 : data = sexp_nth_data (l1, 1, &datalen);
1645 1 : if (!data)
1646 : {
1647 0 : sexp_release (l1);
1648 0 : return GPG_ERR_NO_OBJ;
1649 : }
1650 :
1651 1 : _gcry_md_write (md, data, datalen);
1652 1 : sexp_release (l1);
1653 :
1654 1 : return 0;
1655 : }
1656 :
1657 :
1658 :
1659 :
1660 : /*
1661 : Self-test section.
1662 : */
1663 :
1664 : static const char *
1665 2 : selftest_sign_2048 (gcry_sexp_t pkey, gcry_sexp_t skey)
1666 : {
1667 : static const char sample_data[] =
1668 : "(data (flags pkcs1)"
1669 : " (hash sha256 #11223344556677889900aabbccddeeff"
1670 : /**/ "102030405060708090a0b0c0d0f01121#))";
1671 : static const char sample_data_bad[] =
1672 : "(data (flags pkcs1)"
1673 : " (hash sha256 #11223344556677889900aabbccddeeff"
1674 : /**/ "802030405060708090a0b0c0d0f01121#))";
1675 :
1676 2 : const char *errtxt = NULL;
1677 : gcry_error_t err;
1678 2 : gcry_sexp_t data = NULL;
1679 2 : gcry_sexp_t data_bad = NULL;
1680 2 : gcry_sexp_t sig = NULL;
1681 : /* raw signature data reference */
1682 2 : const char ref_data[] =
1683 : "6252a19a11e1d5155ed9376036277193d644fa239397fff03e9b92d6f86415d6"
1684 : "d30da9273775f290e580d038295ff8ff89522becccfa6ae870bf76b76df402a8"
1685 : "54f69347e3db3de8e1e7d4dada281ec556810c7a8ecd0b5f51f9b1c0e7aa7557"
1686 : "61aa2b8ba5f811304acc6af0eca41fe49baf33bf34eddaf44e21e036ac7f0b68"
1687 : "03cdef1c60021fb7b5b97ebacdd88ab755ce29af568dbc5728cc6e6eff42618d"
1688 : "62a0386ca8beed46402bdeeef29b6a3feded906bace411a06a39192bf516ae10"
1689 : "67e4320fa8ea113968525f4574d022a3ceeaafdc41079efe1f22cc94bf59d8d3"
1690 : "328085da9674857db56de5978a62394aab48aa3b72e23a1b16260cfd9daafe65";
1691 2 : gcry_mpi_t ref_mpi = NULL;
1692 2 : gcry_mpi_t sig_mpi = NULL;
1693 :
1694 2 : err = sexp_sscan (&data, NULL, sample_data, strlen (sample_data));
1695 2 : if (!err)
1696 2 : err = sexp_sscan (&data_bad, NULL,
1697 : sample_data_bad, strlen (sample_data_bad));
1698 2 : if (err)
1699 : {
1700 0 : errtxt = "converting data failed";
1701 0 : goto leave;
1702 : }
1703 :
1704 2 : err = _gcry_pk_sign (&sig, data, skey);
1705 2 : if (err)
1706 : {
1707 0 : errtxt = "signing failed";
1708 0 : goto leave;
1709 : }
1710 :
1711 2 : err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL);
1712 2 : if (err)
1713 : {
1714 0 : errtxt = "converting ref_data to mpi failed";
1715 0 : goto leave;
1716 : }
1717 :
1718 2 : err = _gcry_sexp_extract_param(sig, "sig-val!rsa", "s", &sig_mpi, NULL);
1719 2 : if (err)
1720 : {
1721 0 : errtxt = "extracting signature data failed";
1722 0 : goto leave;
1723 : }
1724 :
1725 2 : if (mpi_cmp (sig_mpi, ref_mpi))
1726 : {
1727 0 : errtxt = "signature does not match reference data";
1728 0 : goto leave;
1729 : }
1730 :
1731 2 : err = _gcry_pk_verify (sig, data, pkey);
1732 2 : if (err)
1733 : {
1734 0 : errtxt = "verify failed";
1735 0 : goto leave;
1736 : }
1737 2 : err = _gcry_pk_verify (sig, data_bad, pkey);
1738 2 : if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
1739 : {
1740 0 : errtxt = "bad signature not detected";
1741 0 : goto leave;
1742 : }
1743 :
1744 :
1745 : leave:
1746 2 : sexp_release (sig);
1747 2 : sexp_release (data_bad);
1748 2 : sexp_release (data);
1749 2 : _gcry_mpi_release (ref_mpi);
1750 2 : _gcry_mpi_release (sig_mpi);
1751 2 : return errtxt;
1752 : }
1753 :
1754 :
1755 :
1756 : /* Given an S-expression ENCR_DATA of the form:
1757 :
1758 : (enc-val
1759 : (rsa
1760 : (a a-value)))
1761 :
1762 : as returned by gcry_pk_decrypt, return the the A-VALUE. On error,
1763 : return NULL. */
1764 : static gcry_mpi_t
1765 2 : extract_a_from_sexp (gcry_sexp_t encr_data)
1766 : {
1767 : gcry_sexp_t l1, l2, l3;
1768 : gcry_mpi_t a_value;
1769 :
1770 2 : l1 = sexp_find_token (encr_data, "enc-val", 0);
1771 2 : if (!l1)
1772 0 : return NULL;
1773 2 : l2 = sexp_find_token (l1, "rsa", 0);
1774 2 : sexp_release (l1);
1775 2 : if (!l2)
1776 0 : return NULL;
1777 2 : l3 = sexp_find_token (l2, "a", 0);
1778 2 : sexp_release (l2);
1779 2 : if (!l3)
1780 0 : return NULL;
1781 2 : a_value = sexp_nth_mpi (l3, 1, 0);
1782 2 : sexp_release (l3);
1783 :
1784 2 : return a_value;
1785 : }
1786 :
1787 :
1788 : static const char *
1789 2 : selftest_encr_2048 (gcry_sexp_t pkey, gcry_sexp_t skey)
1790 : {
1791 2 : const char *errtxt = NULL;
1792 : gcry_error_t err;
1793 : static const char plaintext[] =
1794 : "Jim quickly realized that the beautiful gowns are expensive.";
1795 2 : gcry_sexp_t plain = NULL;
1796 2 : gcry_sexp_t encr = NULL;
1797 2 : gcry_mpi_t ciphertext = NULL;
1798 2 : gcry_sexp_t decr = NULL;
1799 2 : char *decr_plaintext = NULL;
1800 2 : gcry_sexp_t tmplist = NULL;
1801 : /* expected result of encrypting the plaintext with sample_secret_key */
1802 : static const char ref_data[] =
1803 : "18022e2593a402a737caaa93b4c7e750e20ca265452980e1d6b7710fbd3e"
1804 : "7dce72be5c2110fb47691cb38f42170ee3b4a37f2498d4a51567d762585e"
1805 : "4cb81d04fbc7df4144f8e5eac2d4b8688521b64011f11d7ad53f4c874004"
1806 : "819856f2e2a6f83d1c9c4e73ac26089789c14482b0b8d44139133c88c4a5"
1807 : "2dba9dd6d6ffc622666b7d129168333d999706af30a2d7d272db7734e5ed"
1808 : "fb8c64ea3018af3ad20f4a013a5060cb0f5e72753967bebe294280a6ed0d"
1809 : "dbd3c4f11d0a8696e9d32a0dc03deb0b5e49b2cbd1503392642d4e1211f3"
1810 : "e8e2ee38abaa3671ccd57fcde8ca76e85fd2cb77c35706a970a213a27352"
1811 : "cec92a9604d543ddb5fc478ff50e0622";
1812 2 : gcry_mpi_t ref_mpi = NULL;
1813 :
1814 : /* Put the plaintext into an S-expression. */
1815 2 : err = sexp_build (&plain, NULL, "(data (flags raw) (value %s))", plaintext);
1816 2 : if (err)
1817 : {
1818 0 : errtxt = "converting data failed";
1819 0 : goto leave;
1820 : }
1821 :
1822 : /* Encrypt. */
1823 2 : err = _gcry_pk_encrypt (&encr, plain, pkey);
1824 2 : if (err)
1825 : {
1826 0 : errtxt = "encrypt failed";
1827 0 : goto leave;
1828 : }
1829 :
1830 2 : err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL);
1831 2 : if (err)
1832 : {
1833 0 : errtxt = "converting encrydata to mpi failed";
1834 0 : goto leave;
1835 : }
1836 :
1837 : /* Extraxt the ciphertext from the returned S-expression. */
1838 : /*sexp_dump (encr);*/
1839 2 : ciphertext = extract_a_from_sexp (encr);
1840 2 : if (!ciphertext)
1841 : {
1842 0 : errtxt = "gcry_pk_decrypt returned garbage";
1843 0 : goto leave;
1844 : }
1845 :
1846 : /* Check that the ciphertext does no match the plaintext. */
1847 : /* _gcry_log_printmpi ("plaintext", plaintext); */
1848 : /* _gcry_log_printmpi ("ciphertxt", ciphertext); */
1849 2 : if (mpi_cmp (ref_mpi, ciphertext))
1850 : {
1851 0 : errtxt = "ciphertext doesn't match reference data";
1852 0 : goto leave;
1853 : }
1854 :
1855 : /* Decrypt. */
1856 2 : err = _gcry_pk_decrypt (&decr, encr, skey);
1857 2 : if (err)
1858 : {
1859 0 : errtxt = "decrypt failed";
1860 0 : goto leave;
1861 : }
1862 :
1863 : /* Extract the decrypted data from the S-expression. Note that the
1864 : output of gcry_pk_decrypt depends on whether a flags lists occurs
1865 : in its input data. Because we passed the output of
1866 : gcry_pk_encrypt directly to gcry_pk_decrypt, such a flag value
1867 : won't be there as of today. To be prepared for future changes we
1868 : take care of it anyway. */
1869 2 : tmplist = sexp_find_token (decr, "value", 0);
1870 2 : if (tmplist)
1871 0 : decr_plaintext = sexp_nth_string (tmplist, 1);
1872 : else
1873 2 : decr_plaintext = sexp_nth_string (decr, 0);
1874 2 : if (!decr_plaintext)
1875 : {
1876 0 : errtxt = "decrypt returned no plaintext";
1877 0 : goto leave;
1878 : }
1879 :
1880 : /* Check that the decrypted plaintext matches the original plaintext. */
1881 2 : if (strcmp (plaintext, decr_plaintext))
1882 : {
1883 0 : errtxt = "mismatch";
1884 0 : goto leave;
1885 : }
1886 :
1887 : leave:
1888 2 : sexp_release (tmplist);
1889 2 : xfree (decr_plaintext);
1890 2 : sexp_release (decr);
1891 2 : _gcry_mpi_release (ciphertext);
1892 2 : _gcry_mpi_release (ref_mpi);
1893 2 : sexp_release (encr);
1894 2 : sexp_release (plain);
1895 2 : return errtxt;
1896 : }
1897 :
1898 :
1899 : static gpg_err_code_t
1900 2 : selftests_rsa (selftest_report_func_t report)
1901 : {
1902 : const char *what;
1903 : const char *errtxt;
1904 : gcry_error_t err;
1905 2 : gcry_sexp_t skey = NULL;
1906 2 : gcry_sexp_t pkey = NULL;
1907 :
1908 : /* Convert the S-expressions into the internal representation. */
1909 2 : what = "convert";
1910 2 : err = sexp_sscan (&skey, NULL, sample_secret_key, strlen (sample_secret_key));
1911 2 : if (!err)
1912 2 : err = sexp_sscan (&pkey, NULL,
1913 : sample_public_key, strlen (sample_public_key));
1914 2 : if (err)
1915 : {
1916 0 : errtxt = _gcry_strerror (err);
1917 0 : goto failed;
1918 : }
1919 :
1920 2 : what = "key consistency";
1921 2 : err = _gcry_pk_testkey (skey);
1922 2 : if (err)
1923 : {
1924 0 : errtxt = _gcry_strerror (err);
1925 0 : goto failed;
1926 : }
1927 :
1928 2 : what = "sign";
1929 2 : errtxt = selftest_sign_2048 (pkey, skey);
1930 2 : if (errtxt)
1931 0 : goto failed;
1932 :
1933 2 : what = "encrypt";
1934 2 : errtxt = selftest_encr_2048 (pkey, skey);
1935 2 : if (errtxt)
1936 0 : goto failed;
1937 :
1938 2 : sexp_release (pkey);
1939 2 : sexp_release (skey);
1940 2 : return 0; /* Succeeded. */
1941 :
1942 : failed:
1943 0 : sexp_release (pkey);
1944 0 : sexp_release (skey);
1945 0 : if (report)
1946 0 : report ("pubkey", GCRY_PK_RSA, what, errtxt);
1947 0 : return GPG_ERR_SELFTEST_FAILED;
1948 : }
1949 :
1950 :
1951 : /* Run a full self-test for ALGO and return 0 on success. */
1952 : static gpg_err_code_t
1953 2 : run_selftests (int algo, int extended, selftest_report_func_t report)
1954 : {
1955 : gpg_err_code_t ec;
1956 :
1957 : (void)extended;
1958 :
1959 2 : switch (algo)
1960 : {
1961 : case GCRY_PK_RSA:
1962 2 : ec = selftests_rsa (report);
1963 2 : break;
1964 : default:
1965 0 : ec = GPG_ERR_PUBKEY_ALGO;
1966 0 : break;
1967 :
1968 : }
1969 2 : return ec;
1970 : }
1971 :
1972 :
1973 :
1974 :
1975 : gcry_pk_spec_t _gcry_pubkey_spec_rsa =
1976 : {
1977 : GCRY_PK_RSA, { 0, 1 },
1978 : (GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR),
1979 : "RSA", rsa_names,
1980 : "ne", "nedpqu", "a", "s", "n",
1981 : rsa_generate,
1982 : rsa_check_secret_key,
1983 : rsa_encrypt,
1984 : rsa_decrypt,
1985 : rsa_sign,
1986 : rsa_verify,
1987 : rsa_get_nbits,
1988 : run_selftests,
1989 : compute_keygrip
1990 : };
|