1/* crypto/rsa/rsa_eay.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60#include <openssl/err.h>
61#include <openssl/bn.h>
62#include <openssl/rsa.h>
63#include <openssl/rand.h>
64#include <openssl/fips.h>
65
66#if !defined(RSA_NULL) && defined(OPENSSL_FIPS)
67
68static int RSA_eay_public_encrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
69		unsigned char *to, RSA *rsa,int padding);
70static int RSA_eay_private_encrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
71		unsigned char *to, RSA *rsa,int padding);
72static int RSA_eay_public_decrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
73		unsigned char *to, RSA *rsa,int padding);
74static int RSA_eay_private_decrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
75		unsigned char *to, RSA *rsa,int padding);
76static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa);
77static int RSA_eay_init(RSA *rsa);
78static int RSA_eay_finish(RSA *rsa);
79static RSA_METHOD rsa_pkcs1_eay_meth={
80	"Eric Young's PKCS#1 RSA",
81	RSA_eay_public_encrypt,
82	RSA_eay_public_decrypt, /* signature verification */
83	RSA_eay_private_encrypt, /* signing */
84	RSA_eay_private_decrypt,
85	RSA_eay_mod_exp,
86	BN_mod_exp_mont, /* XXX probably we should not use Montgomery if  e == 3 */
87	RSA_eay_init,
88	RSA_eay_finish,
89	0, /* flags */
90	NULL,
91	0, /* rsa_sign */
92	0  /* rsa_verify */
93	};
94
95const RSA_METHOD *RSA_PKCS1_SSLeay(void)
96	{
97	return(&rsa_pkcs1_eay_meth);
98	}
99
100static int RSA_eay_public_encrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
101	     unsigned char *to, RSA *rsa, int padding)
102	{
103	BIGNUM f,ret;
104	int i,j,k,num=0,r= -1;
105	unsigned char *buf=NULL;
106	BN_CTX *ctx=NULL;
107
108	BN_init(&f);
109	BN_init(&ret);
110
111	if(FIPS_selftest_failed())
112		{
113		FIPSerr(FIPS_F_RSA_EAY_PUBLIC_ENCRYPT,FIPS_R_FIPS_SELFTEST_FAILED);
114		goto err;
115		}
116
117	if ((ctx=BN_CTX_new()) == NULL) goto err;
118	num=BN_num_bytes(rsa->n);
119	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
120		{
121		RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT,ERR_R_MALLOC_FAILURE);
122		goto err;
123		}
124
125	switch (padding)
126		{
127	case RSA_PKCS1_PADDING:
128		i=RSA_padding_add_PKCS1_type_2(buf,num,from,flen);
129		break;
130#ifndef OPENSSL_NO_SHA
131	case RSA_PKCS1_OAEP_PADDING:
132	        i=RSA_padding_add_PKCS1_OAEP(buf,num,from,flen,NULL,0);
133		break;
134#endif
135	case RSA_SSLV23_PADDING:
136		i=RSA_padding_add_SSLv23(buf,num,from,flen);
137		break;
138	case RSA_NO_PADDING:
139		i=RSA_padding_add_none(buf,num,from,flen);
140		break;
141	default:
142		RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
143		goto err;
144		}
145	if (i <= 0) goto err;
146
147	if (BN_bin2bn(buf,num,&f) == NULL) goto err;
148
149	if (BN_ucmp(&f, rsa->n) >= 0)
150		{
151		/* usually the padding functions would catch this */
152		RSAerr(RSA_F_RSA_EAY_PUBLIC_ENCRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
153		goto err;
154		}
155
156	if ((rsa->_method_mod_n == NULL) && (rsa->flags & RSA_FLAG_CACHE_PUBLIC))
157		{
158		BN_MONT_CTX* bn_mont_ctx;
159		if ((bn_mont_ctx=BN_MONT_CTX_new()) == NULL)
160			goto err;
161		if (!BN_MONT_CTX_set(bn_mont_ctx,rsa->n,ctx))
162			{
163			BN_MONT_CTX_free(bn_mont_ctx);
164			goto err;
165			}
166		if (rsa->_method_mod_n == NULL) /* other thread may have finished first */
167			{
168			CRYPTO_w_lock(CRYPTO_LOCK_RSA);
169			if (rsa->_method_mod_n == NULL)
170				{
171				rsa->_method_mod_n = bn_mont_ctx;
172				bn_mont_ctx = NULL;
173				}
174			CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
175			}
176		if (bn_mont_ctx)
177			BN_MONT_CTX_free(bn_mont_ctx);
178		}
179
180	if (!rsa->meth->bn_mod_exp(&ret,&f,rsa->e,rsa->n,ctx,
181		rsa->_method_mod_n)) goto err;
182
183	/* put in leading 0 bytes if the number is less than the
184	 * length of the modulus */
185	j=BN_num_bytes(&ret);
186	i=BN_bn2bin(&ret,&(to[num-j]));
187	for (k=0; k<(num-i); k++)
188		to[k]=0;
189
190	r=num;
191err:
192	if (ctx != NULL) BN_CTX_free(ctx);
193	BN_clear_free(&f);
194	BN_clear_free(&ret);
195	if (buf != NULL)
196		{
197		OPENSSL_cleanse(buf,num);
198		OPENSSL_free(buf);
199		}
200	return(r);
201	}
202
203static int rsa_eay_blinding(RSA *rsa, BN_CTX *ctx)
204	{
205	int ret = 1;
206	CRYPTO_w_lock(CRYPTO_LOCK_RSA);
207	/* Check again inside the lock - the macro's check is racey */
208	if(rsa->blinding == NULL)
209		ret = RSA_blinding_on(rsa, ctx);
210	CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
211	return ret;
212	}
213
214#define BLINDING_HELPER(rsa, ctx, err_instr) \
215	do { \
216		if((!((rsa)->flags & RSA_FLAG_NO_BLINDING)) && \
217		    ((rsa)->blinding == NULL) && \
218		    !rsa_eay_blinding(rsa, ctx)) \
219		    err_instr \
220	} while(0)
221
222static BN_BLINDING *setup_blinding(RSA *rsa, BN_CTX *ctx)
223	{
224	BIGNUM *A, *Ai;
225	BN_BLINDING *ret = NULL;
226
227	/* added in OpenSSL 0.9.6j and 0.9.7b */
228
229	/* NB: similar code appears in RSA_blinding_on (rsa_lib.c);
230	 * this should be placed in a new function of its own, but for reasons
231	 * of binary compatibility can't */
232
233	BN_CTX_start(ctx);
234	A = BN_CTX_get(ctx);
235	if ((RAND_status() == 0) && rsa->d != NULL && rsa->d->d != NULL)
236		{
237		/* if PRNG is not properly seeded, resort to secret exponent as unpredictable seed */
238		RAND_add(rsa->d->d, rsa->d->dmax * sizeof rsa->d->d[0], 0);
239		if (!BN_pseudo_rand_range(A,rsa->n)) goto err;
240		}
241	else
242		{
243		if (!BN_rand_range(A,rsa->n)) goto err;
244		}
245	if ((Ai=BN_mod_inverse(NULL,A,rsa->n,ctx)) == NULL) goto err;
246
247	if (!rsa->meth->bn_mod_exp(A,A,rsa->e,rsa->n,ctx,rsa->_method_mod_n))
248		goto err;
249	ret = BN_BLINDING_new(A,Ai,rsa->n);
250	BN_free(Ai);
251err:
252	BN_CTX_end(ctx);
253	return ret;
254	}
255
256/* signing */
257static int RSA_eay_private_encrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
258	     unsigned char *to, RSA *rsa, int padding)
259	{
260	BIGNUM f,ret;
261	int i,j,k,num=0,r= -1;
262	unsigned char *buf=NULL;
263	BN_CTX *ctx=NULL;
264	int local_blinding = 0;
265	BN_BLINDING *blinding = NULL;
266
267	BN_init(&f);
268	BN_init(&ret);
269
270	if ((ctx=BN_CTX_new()) == NULL) goto err;
271	num=BN_num_bytes(rsa->n);
272	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
273		{
274		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,ERR_R_MALLOC_FAILURE);
275		goto err;
276		}
277
278	switch (padding)
279		{
280	case RSA_PKCS1_PADDING:
281		i=RSA_padding_add_PKCS1_type_1(buf,num,from,flen);
282		break;
283	case RSA_NO_PADDING:
284		i=RSA_padding_add_none(buf,num,from,flen);
285		break;
286	case RSA_SSLV23_PADDING:
287	default:
288		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
289		goto err;
290		}
291	if (i <= 0) goto err;
292
293	if (BN_bin2bn(buf,num,&f) == NULL) goto err;
294
295	if (BN_ucmp(&f, rsa->n) >= 0)
296		{
297		/* usually the padding functions would catch this */
298		RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
299		goto err;
300		}
301
302	BLINDING_HELPER(rsa, ctx, goto err;);
303	blinding = rsa->blinding;
304
305	/* Now unless blinding is disabled, 'blinding' is non-NULL.
306	 * But the BN_BLINDING object may be owned by some other thread
307	 * (we don't want to keep it constant and we don't want to use
308	 * lots of locking to avoid race conditions, so only a single
309	 * thread can use it; other threads have to use local blinding
310	 * factors) */
311	if (!(rsa->flags & RSA_FLAG_NO_BLINDING))
312		{
313		if (blinding == NULL)
314			{
315			RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
316			goto err;
317			}
318		}
319
320	if (blinding != NULL)
321		{
322		if (blinding->thread_id != CRYPTO_thread_id())
323			{
324			/* we need a local one-time blinding factor */
325
326			blinding = setup_blinding(rsa, ctx);
327			if (blinding == NULL)
328				goto err;
329			local_blinding = 1;
330			}
331		}
332
333	if (blinding)
334		if (!BN_BLINDING_convert(&f, blinding, ctx)) goto err;
335
336	if ( (rsa->flags & RSA_FLAG_EXT_PKEY) ||
337		((rsa->p != NULL) &&
338		(rsa->q != NULL) &&
339		(rsa->dmp1 != NULL) &&
340		(rsa->dmq1 != NULL) &&
341		(rsa->iqmp != NULL)) )
342		{ if (!rsa->meth->rsa_mod_exp(&ret,&f,rsa)) goto err; }
343	else
344		{
345		if (!rsa->meth->bn_mod_exp(&ret,&f,rsa->d,rsa->n,ctx,NULL)) goto err;
346		}
347
348	if (blinding)
349		if (!BN_BLINDING_invert(&ret, blinding, ctx)) goto err;
350
351	/* put in leading 0 bytes if the number is less than the
352	 * length of the modulus */
353	j=BN_num_bytes(&ret);
354	i=BN_bn2bin(&ret,&(to[num-j]));
355	for (k=0; k<(num-i); k++)
356		to[k]=0;
357
358	r=num;
359err:
360	if (ctx != NULL) BN_CTX_free(ctx);
361	BN_clear_free(&ret);
362	BN_clear_free(&f);
363	if (local_blinding)
364		BN_BLINDING_free(blinding);
365	if (buf != NULL)
366		{
367		OPENSSL_cleanse(buf,num);
368		OPENSSL_free(buf);
369		}
370	return(r);
371	}
372
373static int RSA_eay_private_decrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
374	     unsigned char *to, RSA *rsa, int padding)
375	{
376	BIGNUM f,ret;
377	int j,num=0,r= -1;
378	unsigned char *p;
379	unsigned char *buf=NULL;
380	BN_CTX *ctx=NULL;
381	int local_blinding = 0;
382	BN_BLINDING *blinding = NULL;
383
384	BN_init(&f);
385	BN_init(&ret);
386	ctx=BN_CTX_new();
387	if (ctx == NULL) goto err;
388
389	num=BN_num_bytes(rsa->n);
390
391	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
392		{
393		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,ERR_R_MALLOC_FAILURE);
394		goto err;
395		}
396
397	/* This check was for equality but PGP does evil things
398	 * and chops off the top '0' bytes */
399	if (flen > num)
400		{
401		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_DATA_GREATER_THAN_MOD_LEN);
402		goto err;
403		}
404
405	/* make data into a big number */
406	if (BN_bin2bn(from,(int)flen,&f) == NULL) goto err;
407
408	if (BN_ucmp(&f, rsa->n) >= 0)
409		{
410		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
411		goto err;
412		}
413
414	BLINDING_HELPER(rsa, ctx, goto err;);
415	blinding = rsa->blinding;
416
417	/* Now unless blinding is disabled, 'blinding' is non-NULL.
418	 * But the BN_BLINDING object may be owned by some other thread
419	 * (we don't want to keep it constant and we don't want to use
420	 * lots of locking to avoid race conditions, so only a single
421	 * thread can use it; other threads have to use local blinding
422	 * factors) */
423	if (!(rsa->flags & RSA_FLAG_NO_BLINDING))
424		{
425		if (blinding == NULL)
426			{
427			RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, ERR_R_INTERNAL_ERROR);
428			goto err;
429			}
430		}
431
432	if (blinding != NULL)
433		{
434		if (blinding->thread_id != CRYPTO_thread_id())
435			{
436			/* we need a local one-time blinding factor */
437
438			blinding = setup_blinding(rsa, ctx);
439			if (blinding == NULL)
440				goto err;
441			local_blinding = 1;
442			}
443		}
444
445	if (blinding)
446		if (!BN_BLINDING_convert(&f, blinding, ctx)) goto err;
447
448	/* do the decrypt */
449	if ( (rsa->flags & RSA_FLAG_EXT_PKEY) ||
450		((rsa->p != NULL) &&
451		(rsa->q != NULL) &&
452		(rsa->dmp1 != NULL) &&
453		(rsa->dmq1 != NULL) &&
454		(rsa->iqmp != NULL)) )
455		{ if (!rsa->meth->rsa_mod_exp(&ret,&f,rsa)) goto err; }
456	else
457		{
458		if (!rsa->meth->bn_mod_exp(&ret,&f,rsa->d,rsa->n,ctx,NULL))
459			goto err;
460		}
461
462	if (blinding)
463		if (!BN_BLINDING_invert(&ret, blinding, ctx)) goto err;
464
465	p=buf;
466	j=BN_bn2bin(&ret,p); /* j is only used with no-padding mode */
467
468	switch (padding)
469		{
470	case RSA_PKCS1_PADDING:
471		r=RSA_padding_check_PKCS1_type_2(to,num,buf,j,num);
472		break;
473#ifndef OPENSSL_NO_SHA
474        case RSA_PKCS1_OAEP_PADDING:
475	        r=RSA_padding_check_PKCS1_OAEP(to,num,buf,j,num,NULL,0);
476                break;
477#endif
478 	case RSA_SSLV23_PADDING:
479		r=RSA_padding_check_SSLv23(to,num,buf,j,num);
480		break;
481	case RSA_NO_PADDING:
482		r=RSA_padding_check_none(to,num,buf,j,num);
483		break;
484	default:
485		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
486		goto err;
487		}
488	if (r < 0)
489		RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT,RSA_R_PADDING_CHECK_FAILED);
490
491err:
492	if (ctx != NULL) BN_CTX_free(ctx);
493	BN_clear_free(&f);
494	BN_clear_free(&ret);
495	if (local_blinding)
496		BN_BLINDING_free(blinding);
497	if (buf != NULL)
498		{
499		OPENSSL_cleanse(buf,num);
500		OPENSSL_free(buf);
501		}
502	return(r);
503	}
504
505/* signature verification */
506static int RSA_eay_public_decrypt(FIPS_RSA_SIZE_T flen, const unsigned char *from,
507	     unsigned char *to, RSA *rsa, int padding)
508	{
509	BIGNUM f,ret;
510	int i,num=0,r= -1;
511	unsigned char *p;
512	unsigned char *buf=NULL;
513	BN_CTX *ctx=NULL;
514
515	BN_init(&f);
516	BN_init(&ret);
517	ctx=BN_CTX_new();
518	if (ctx == NULL) goto err;
519
520	num=BN_num_bytes(rsa->n);
521	buf=(unsigned char *)OPENSSL_malloc(num);
522	if (buf == NULL)
523		{
524		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,ERR_R_MALLOC_FAILURE);
525		goto err;
526		}
527
528	/* This check was for equality but PGP does evil things
529	 * and chops off the top '0' bytes */
530	if (flen > num)
531		{
532		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_GREATER_THAN_MOD_LEN);
533		goto err;
534		}
535
536	if (BN_bin2bn(from,flen,&f) == NULL) goto err;
537
538	if (BN_ucmp(&f, rsa->n) >= 0)
539		{
540		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
541		goto err;
542		}
543
544	/* do the decrypt */
545	if ((rsa->_method_mod_n == NULL) && (rsa->flags & RSA_FLAG_CACHE_PUBLIC))
546		{
547		BN_MONT_CTX* bn_mont_ctx;
548		if ((bn_mont_ctx=BN_MONT_CTX_new()) == NULL)
549			goto err;
550		if (!BN_MONT_CTX_set(bn_mont_ctx,rsa->n,ctx))
551			{
552			BN_MONT_CTX_free(bn_mont_ctx);
553			goto err;
554			}
555		if (rsa->_method_mod_n == NULL) /* other thread may have finished first */
556			{
557			CRYPTO_w_lock(CRYPTO_LOCK_RSA);
558			if (rsa->_method_mod_n == NULL)
559				{
560				rsa->_method_mod_n = bn_mont_ctx;
561				bn_mont_ctx = NULL;
562				}
563			CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
564			}
565		if (bn_mont_ctx)
566			BN_MONT_CTX_free(bn_mont_ctx);
567		}
568
569	if (!rsa->meth->bn_mod_exp(&ret,&f,rsa->e,rsa->n,ctx,
570		rsa->_method_mod_n)) goto err;
571
572	p=buf;
573	i=BN_bn2bin(&ret,p);
574
575	switch (padding)
576		{
577	case RSA_PKCS1_PADDING:
578		r=RSA_padding_check_PKCS1_type_1(to,num,buf,i,num);
579		break;
580	case RSA_NO_PADDING:
581		r=RSA_padding_check_none(to,num,buf,i,num);
582		break;
583	default:
584		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_UNKNOWN_PADDING_TYPE);
585		goto err;
586		}
587	if (r < 0)
588		RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_PADDING_CHECK_FAILED);
589
590err:
591	if (ctx != NULL) BN_CTX_free(ctx);
592	BN_clear_free(&f);
593	BN_clear_free(&ret);
594	if (buf != NULL)
595		{
596		OPENSSL_cleanse(buf,num);
597		OPENSSL_free(buf);
598		}
599	return(r);
600	}
601
602static int RSA_eay_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
603	{
604	BIGNUM r1,m1,vrfy;
605	int ret=0;
606	BN_CTX *ctx;
607
608	BN_init(&m1);
609	BN_init(&r1);
610	BN_init(&vrfy);
611	if ((ctx=BN_CTX_new()) == NULL) goto err;
612
613	if (rsa->flags & RSA_FLAG_CACHE_PRIVATE)
614		{
615		if (rsa->_method_mod_p == NULL)
616			{
617			BN_MONT_CTX* bn_mont_ctx;
618			if ((bn_mont_ctx=BN_MONT_CTX_new()) == NULL)
619				goto err;
620			if (!BN_MONT_CTX_set(bn_mont_ctx,rsa->p,ctx))
621				{
622				BN_MONT_CTX_free(bn_mont_ctx);
623				goto err;
624				}
625			if (rsa->_method_mod_p == NULL) /* other thread may have finished first */
626				{
627				CRYPTO_w_lock(CRYPTO_LOCK_RSA);
628				if (rsa->_method_mod_p == NULL)
629					{
630					rsa->_method_mod_p = bn_mont_ctx;
631					bn_mont_ctx = NULL;
632					}
633				CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
634				}
635			if (bn_mont_ctx)
636				BN_MONT_CTX_free(bn_mont_ctx);
637			}
638
639		if (rsa->_method_mod_q == NULL)
640			{
641			BN_MONT_CTX* bn_mont_ctx;
642			if ((bn_mont_ctx=BN_MONT_CTX_new()) == NULL)
643				goto err;
644			if (!BN_MONT_CTX_set(bn_mont_ctx,rsa->q,ctx))
645				{
646				BN_MONT_CTX_free(bn_mont_ctx);
647				goto err;
648				}
649			if (rsa->_method_mod_q == NULL) /* other thread may have finished first */
650				{
651				CRYPTO_w_lock(CRYPTO_LOCK_RSA);
652				if (rsa->_method_mod_q == NULL)
653					{
654					rsa->_method_mod_q = bn_mont_ctx;
655					bn_mont_ctx = NULL;
656					}
657				CRYPTO_w_unlock(CRYPTO_LOCK_RSA);
658				}
659			if (bn_mont_ctx)
660				BN_MONT_CTX_free(bn_mont_ctx);
661			}
662		}
663
664	if (!BN_mod(&r1,I,rsa->q,ctx)) goto err;
665	if (!rsa->meth->bn_mod_exp(&m1,&r1,rsa->dmq1,rsa->q,ctx,
666		rsa->_method_mod_q)) goto err;
667
668	if (!BN_mod(&r1,I,rsa->p,ctx)) goto err;
669	if (!rsa->meth->bn_mod_exp(r0,&r1,rsa->dmp1,rsa->p,ctx,
670		rsa->_method_mod_p)) goto err;
671
672	if (!BN_sub(r0,r0,&m1)) goto err;
673	/* This will help stop the size of r0 increasing, which does
674	 * affect the multiply if it optimised for a power of 2 size */
675	if (r0->neg)
676		if (!BN_add(r0,r0,rsa->p)) goto err;
677
678	if (!BN_mul(&r1,r0,rsa->iqmp,ctx)) goto err;
679	if (!BN_mod(r0,&r1,rsa->p,ctx)) goto err;
680	/* If p < q it is occasionally possible for the correction of
681         * adding 'p' if r0 is negative above to leave the result still
682	 * negative. This can break the private key operations: the following
683	 * second correction should *always* correct this rare occurrence.
684	 * This will *never* happen with OpenSSL generated keys because
685         * they ensure p > q [steve]
686         */
687	if (r0->neg)
688		if (!BN_add(r0,r0,rsa->p)) goto err;
689	if (!BN_mul(&r1,r0,rsa->q,ctx)) goto err;
690	if (!BN_add(r0,&r1,&m1)) goto err;
691
692	if (rsa->e && rsa->n)
693		{
694		if (!rsa->meth->bn_mod_exp(&vrfy,r0,rsa->e,rsa->n,ctx,NULL)) goto err;
695		/* If 'I' was greater than (or equal to) rsa->n, the operation
696		 * will be equivalent to using 'I mod n'. However, the result of
697		 * the verify will *always* be less than 'n' so we don't check
698		 * for absolute equality, just congruency. */
699		if (!BN_sub(&vrfy, &vrfy, I)) goto err;
700		if (!BN_mod(&vrfy, &vrfy, rsa->n, ctx)) goto err;
701		if (vrfy.neg)
702			if (!BN_add(&vrfy, &vrfy, rsa->n)) goto err;
703		if (!BN_is_zero(&vrfy))
704			/* 'I' and 'vrfy' aren't congruent mod n. Don't leak
705			 * miscalculated CRT output, just do a raw (slower)
706			 * mod_exp and return that instead. */
707			if (!rsa->meth->bn_mod_exp(r0,I,rsa->d,rsa->n,ctx,NULL)) goto err;
708		}
709	ret=1;
710err:
711	BN_clear_free(&m1);
712	BN_clear_free(&r1);
713	BN_clear_free(&vrfy);
714	BN_CTX_free(ctx);
715	return(ret);
716	}
717
718static int RSA_eay_init(RSA *rsa)
719	{
720	rsa->flags|=RSA_FLAG_CACHE_PUBLIC|RSA_FLAG_CACHE_PRIVATE;
721	return(1);
722	}
723
724static int RSA_eay_finish(RSA *rsa)
725	{
726	if (rsa->_method_mod_n != NULL)
727		BN_MONT_CTX_free(rsa->_method_mod_n);
728	if (rsa->_method_mod_p != NULL)
729		BN_MONT_CTX_free(rsa->_method_mod_p);
730	if (rsa->_method_mod_q != NULL)
731		BN_MONT_CTX_free(rsa->_method_mod_q);
732	return(1);
733	}
734
735#endif
736