1178479Sjb/* crypto/bn/bn_mont.c */
2178479Sjb/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3178479Sjb * All rights reserved.
4178479Sjb *
5210767Srpaulo * This package is an SSL implementation written
6210767Srpaulo * by Eric Young (eay@cryptsoft.com).
7178479Sjb * The implementation was written so as to conform with Netscapes SSL.
8178479Sjb *
9178479Sjb * This library is free for commercial and non-commercial use as long as
10178479Sjb * the following conditions are aheared to.  The following conditions
11178479Sjb * apply to all code found in this distribution, be it the RC4, RSA,
12178479Sjb * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13178479Sjb * included with this distribution is covered by the same copyright terms
14178479Sjb * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15178479Sjb *
16178479Sjb * Copyright remains Eric Young's, and as such any Copyright notices in
17178479Sjb * the code are not to be removed.
18178479Sjb * If this package is used in a product, Eric Young should be given attribution
19178479Sjb * as the author of the parts of the library used.
20178479Sjb * This can be in the form of a textual message at program startup or
21178479Sjb * in documentation (online or textual) provided with the package.
22210767Srpaulo *
23269245Smarkj * Redistribution and use in source and binary forms, with or without
24178479Sjb * modification, are permitted provided that the following conditions
25178479Sjb * are met:
26178479Sjb * 1. Redistributions of source code must retain the copyright
27178479Sjb *    notice, this list of conditions and the following disclaimer.
28178479Sjb * 2. Redistributions in binary form must reproduce the above copyright
29178479Sjb *    notice, this list of conditions and the following disclaimer in the
30178479Sjb *    documentation and/or other materials provided with the distribution.
31178479Sjb * 3. All advertising materials mentioning features or use of this software
32178479Sjb *    must display the following acknowledgement:
33178479Sjb *    "This product includes cryptographic software written by
34178479Sjb *     Eric Young (eay@cryptsoft.com)"
35178479Sjb *    The word 'cryptographic' can be left out if the rouines from the library
36178479Sjb *    being used are not cryptographic related :-).
37178479Sjb * 4. If you include any Windows specific code (or a derivative thereof) from
38211554Srpaulo *    the apps directory (application code) you must include an acknowledgement:
39211554Srpaulo *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40178479Sjb *
41178479Sjb * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42178479Sjb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43178479Sjb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44178479Sjb * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45178479Sjb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46178479Sjb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47178479Sjb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48178479Sjb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49178479Sjb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50178479Sjb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51178479Sjb * SUCH DAMAGE.
52178479Sjb *
53178479Sjb * The licence and distribution terms for any publically available version or
54178479Sjb * derivative of this code cannot be changed.  i.e. this code cannot simply be
55178479Sjb * copied and put under another distribution licence
56178479Sjb * [including the GNU Public Licence.]
57178479Sjb */
58178572Sjb/* ====================================================================
59211554Srpaulo * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60178479Sjb *
61211554Srpaulo * Redistribution and use in source and binary forms, with or without
62178479Sjb * modification, are permitted provided that the following conditions
63178479Sjb * are met:
64178479Sjb *
65211554Srpaulo * 1. Redistributions of source code must retain the above copyright
66178479Sjb *    notice, this list of conditions and the following disclaimer.
67211554Srpaulo *
68212462Srpaulo * 2. Redistributions in binary form must reproduce the above copyright
69178479Sjb *    notice, this list of conditions and the following disclaimer in
70178479Sjb *    the documentation and/or other materials provided with the
71178479Sjb *    distribution.
72178479Sjb *
73178479Sjb * 3. All advertising materials mentioning features or use of this
74178479Sjb *    software must display the following acknowledgment:
75210767Srpaulo *    "This product includes software developed by the OpenSSL Project
76178479Sjb *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77178479Sjb *
78178479Sjb * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79178479Sjb *    endorse or promote products derived from this software without
80178479Sjb *    prior written permission. For written permission, please contact
81178479Sjb *    openssl-core@openssl.org.
82178479Sjb *
83178479Sjb * 5. Products derived from this software may not be called "OpenSSL"
84178479Sjb *    nor may "OpenSSL" appear in their names without prior written
85178479Sjb *    permission of the OpenSSL Project.
86178479Sjb *
87178479Sjb * 6. Redistributions of any form whatsoever must retain the following
88178479Sjb *    acknowledgment:
89178479Sjb *    "This product includes software developed by the OpenSSL Project
90178479Sjb *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91178479Sjb *
92178479Sjb * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93211554Srpaulo * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94211554Srpaulo * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95211554Srpaulo * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96211554Srpaulo * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97211554Srpaulo * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98211554Srpaulo * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99211554Srpaulo * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100211554Srpaulo * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101211554Srpaulo * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102211554Srpaulo * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103211554Srpaulo * OF THE POSSIBILITY OF SUCH DAMAGE.
104211554Srpaulo * ====================================================================
105211554Srpaulo *
106228547Sdim * This product includes cryptographic software written by Eric Young
107211554Srpaulo * (eay@cryptsoft.com).  This product includes software written by Tim
108211554Srpaulo * Hudson (tjh@cryptsoft.com).
109211554Srpaulo *
110211554Srpaulo */
111211554Srpaulo
112211554Srpaulo/*
113211554Srpaulo * Details about Montgomery multiplication algorithms can be found at
114211554Srpaulo * http://security.ece.orst.edu/publications.html, e.g.
115211554Srpaulo * http://security.ece.orst.edu/koc/papers/j37acmon.pdf and
116211554Srpaulo * sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf
117211554Srpaulo */
118211554Srpaulo
119211554Srpaulo#include <stdio.h>
120211554Srpaulo#include "cryptlib.h"
121211554Srpaulo#include "bn_lcl.h"
122211554Srpaulo
123178572Sjb#define MONT_WORD /* use the faster word-based algorithm */
124178479Sjb
125178572Sjb#ifdef MONT_WORD
126178572Sjbstatic int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
127178572Sjb#endif
128178572Sjb
129178479Sjbint BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
130178479Sjb			  BN_MONT_CTX *mont, BN_CTX *ctx)
131178479Sjb	{
132211554Srpaulo	BIGNUM *tmp;
133178479Sjb	int ret=0;
134211554Srpaulo#if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
135211554Srpaulo	int num = mont->N.top;
136211554Srpaulo
137178479Sjb	if (num>1 && a->top==num && b->top==num)
138178479Sjb		{
139178479Sjb		if (bn_wexpand(r,num) == NULL) return(0);
140178479Sjb		if (bn_mul_mont(r->d,a->d,b->d,mont->N.d,mont->n0,num))
141178479Sjb			{
142178479Sjb			r->neg = a->neg^b->neg;
143211554Srpaulo			r->top = num;
144178572Sjb			bn_correct_top(r);
145178479Sjb			return(1);
146178572Sjb			}
147178572Sjb		}
148269245Smarkj#endif
149269245Smarkj
150211554Srpaulo	BN_CTX_start(ctx);
151178572Sjb	tmp = BN_CTX_get(ctx);
152178479Sjb	if (tmp == NULL) goto err;
153178479Sjb
154211554Srpaulo	bn_check_top(tmp);
155211554Srpaulo	if (a == b)
156211554Srpaulo		{
157269245Smarkj		if (!BN_sqr(tmp,a,ctx)) goto err;
158269245Smarkj		}
159211554Srpaulo	else
160211554Srpaulo		{
161211554Srpaulo		if (!BN_mul(tmp,a,b,ctx)) goto err;
162269245Smarkj		}
163211554Srpaulo	/* reduce from aRR to aR */
164211554Srpaulo#ifdef MONT_WORD
165269245Smarkj	if (!BN_from_montgomery_word(r,tmp,mont)) goto err;
166211554Srpaulo#else
167178479Sjb	if (!BN_from_montgomery(r,tmp,mont,ctx)) goto err;
168178479Sjb#endif
169178479Sjb	bn_check_top(r);
170178479Sjb	ret=1;
171210767Srpauloerr:
172210767Srpaulo	BN_CTX_end(ctx);
173210767Srpaulo	return(ret);
174178479Sjb	}
175178479Sjb
176178479Sjb#ifdef MONT_WORD
177178479Sjbstatic int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
178178479Sjb	{
179178572Sjb	BIGNUM *n;
180178479Sjb	BN_ULONG *ap,*np,*rp,n0,v,carry;
181178479Sjb	int nl,max,i;
182178479Sjb
183178479Sjb	n= &(mont->N);
184178572Sjb	nl=n->top;
185178479Sjb	if (nl == 0) { ret->top=0; return(1); }
186211554Srpaulo
187178479Sjb	max=(2*nl); /* carry is stored separately */
188178479Sjb	if (bn_wexpand(r,max) == NULL) return(0);
189178479Sjb
190178479Sjb	r->neg^=n->neg;
191211554Srpaulo	np=n->d;
192211554Srpaulo	rp=r->d;
193211554Srpaulo
194211554Srpaulo	/* clear the top words of T */
195211554Srpaulo#if 1
196211554Srpaulo	for (i=r->top; i<max; i++) /* memset? XXX */
197211554Srpaulo		rp[i]=0;
198211554Srpaulo#else
199211554Srpaulo	memset(&(rp[r->top]),0,(max-r->top)*sizeof(BN_ULONG));
200211554Srpaulo#endif
201211554Srpaulo
202211554Srpaulo	r->top=max;
203211554Srpaulo	n0=mont->n0[0];
204211554Srpaulo
205211554Srpaulo#ifdef BN_COUNT
206211554Srpaulo	fprintf(stderr,"word BN_from_montgomery_word %d * %d\n",nl,nl);
207211554Srpaulo#endif
208211554Srpaulo	for (carry=0, i=0; i<nl; i++, rp++)
209211554Srpaulo		{
210211554Srpaulo#ifdef __TANDEM
211211554Srpaulo                {
212211554Srpaulo                   long long t1;
213211554Srpaulo                   long long t2;
214211554Srpaulo                   long long t3;
215269245Smarkj                   t1 = rp[0] * (n0 & 0177777);
216269245Smarkj                   t2 = 037777600000l;
217211554Srpaulo                   t2 = n0 & t2;
218211554Srpaulo                   t3 = rp[0] & 0177777;
219211554Srpaulo                   t2 = (t3 * t2) & BN_MASK2;
220211554Srpaulo                   t1 = t1 + t2;
221211554Srpaulo                   v=bn_mul_add_words(rp,np,nl,(BN_ULONG) t1);
222211554Srpaulo                }
223211554Srpaulo#else
224211554Srpaulo		v=bn_mul_add_words(rp,np,nl,(rp[0]*n0)&BN_MASK2);
225211554Srpaulo#endif
226269245Smarkj		v = (v+carry+rp[nl])&BN_MASK2;
227269245Smarkj		carry |= (v != rp[nl]);
228269245Smarkj		carry &= (v <= rp[nl]);
229269245Smarkj		rp[nl]=v;
230211554Srpaulo		}
231178479Sjb
232178479Sjb	if (bn_wexpand(ret,nl) == NULL) return(0);
233178479Sjb	ret->top=nl;
234178479Sjb	ret->neg=r->neg;
235178479Sjb
236178479Sjb	rp=ret->d;
237178479Sjb	ap=&(r->d[nl]);
238178479Sjb
239178479Sjb#define BRANCH_FREE 1
240178479Sjb#if BRANCH_FREE
241178479Sjb	{
242178479Sjb	BN_ULONG *nrp;
243178572Sjb	size_t m;
244178479Sjb
245178479Sjb	v=bn_sub_words(rp,ap,np,nl)-carry;
246178479Sjb	/* if subtraction result is real, then
247178479Sjb	 * trick unconditional memcpy below to perform in-place
248178479Sjb	 * "refresh" instead of actual copy. */
249178479Sjb	m=(0-(size_t)v);
250178479Sjb	nrp=(BN_ULONG *)(((PTR_SIZE_INT)rp&~m)|((PTR_SIZE_INT)ap&m));
251178479Sjb
252178479Sjb	for (i=0,nl-=4; i<nl; i+=4)
253178479Sjb		{
254178572Sjb		BN_ULONG t1,t2,t3,t4;
255178479Sjb
256178572Sjb		t1=nrp[i+0];
257178572Sjb		t2=nrp[i+1];
258211554Srpaulo		t3=nrp[i+2];	ap[i+0]=0;
259178479Sjb		t4=nrp[i+3];	ap[i+1]=0;
260178479Sjb		rp[i+0]=t1;	ap[i+2]=0;
261178479Sjb		rp[i+1]=t2;	ap[i+3]=0;
262178479Sjb		rp[i+2]=t3;
263178479Sjb		rp[i+3]=t4;
264178479Sjb		}
265178479Sjb	for (nl+=4; i<nl; i++)
266178572Sjb		rp[i]=nrp[i], ap[i]=0;
267178479Sjb	}
268178572Sjb#else
269178572Sjb	if (bn_sub_words (rp,ap,np,nl)-carry)
270178479Sjb		memcpy(rp,ap,nl*sizeof(BN_ULONG));
271178479Sjb#endif
272211554Srpaulo	bn_correct_top(r);
273211554Srpaulo	bn_correct_top(ret);
274211554Srpaulo	bn_check_top(ret);
275178479Sjb
276211554Srpaulo	return(1);
277211554Srpaulo	}
278211554Srpaulo#endif	/* MONT_WORD */
279211554Srpaulo
280211554Srpauloint BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
281211554Srpaulo	     BN_CTX *ctx)
282211554Srpaulo	{
283211554Srpaulo	int retn=0;
284211554Srpaulo#ifdef MONT_WORD
285211554Srpaulo	BIGNUM *t;
286211554Srpaulo
287211554Srpaulo	BN_CTX_start(ctx);
288211554Srpaulo	if ((t = BN_CTX_get(ctx)) && BN_copy(t,a))
289211554Srpaulo		retn = BN_from_montgomery_word(ret,t,mont);
290211554Srpaulo	BN_CTX_end(ctx);
291211554Srpaulo#else /* !MONT_WORD */
292211554Srpaulo	BIGNUM *t1,*t2;
293211554Srpaulo
294211554Srpaulo	BN_CTX_start(ctx);
295211554Srpaulo	t1 = BN_CTX_get(ctx);
296211554Srpaulo	t2 = BN_CTX_get(ctx);
297211554Srpaulo	if (t1 == NULL || t2 == NULL) goto err;
298211554Srpaulo
299211554Srpaulo	if (!BN_copy(t1,a)) goto err;
300211554Srpaulo	BN_mask_bits(t1,mont->ri);
301269245Smarkj
302211554Srpaulo	if (!BN_mul(t2,t1,&mont->Ni,ctx)) goto err;
303211554Srpaulo	BN_mask_bits(t2,mont->ri);
304269245Smarkj
305269245Smarkj	if (!BN_mul(t1,t2,&mont->N,ctx)) goto err;
306269245Smarkj	if (!BN_add(t2,a,t1)) goto err;
307269245Smarkj	if (!BN_rshift(ret,t2,mont->ri)) goto err;
308269245Smarkj
309269245Smarkj	if (BN_ucmp(ret, &(mont->N)) >= 0)
310269245Smarkj		{
311269245Smarkj		if (!BN_usub(ret,ret,&(mont->N))) goto err;
312269245Smarkj		}
313269245Smarkj	retn=1;
314211554Srpaulo	bn_check_top(ret);
315269245Smarkj err:
316269245Smarkj	BN_CTX_end(ctx);
317269245Smarkj#endif /* MONT_WORD */
318269245Smarkj	return(retn);
319269245Smarkj	}
320269245Smarkj
321269245SmarkjBN_MONT_CTX *BN_MONT_CTX_new(void)
322269245Smarkj	{
323269245Smarkj	BN_MONT_CTX *ret;
324269245Smarkj
325269245Smarkj	if ((ret=(BN_MONT_CTX *)OPENSSL_malloc(sizeof(BN_MONT_CTX))) == NULL)
326269245Smarkj		return(NULL);
327269245Smarkj
328269245Smarkj	BN_MONT_CTX_init(ret);
329269245Smarkj	ret->flags=BN_FLG_MALLOCED;
330269245Smarkj	return(ret);
331269245Smarkj	}
332269245Smarkj
333269245Smarkjvoid BN_MONT_CTX_init(BN_MONT_CTX *ctx)
334269245Smarkj	{
335269245Smarkj	ctx->ri=0;
336269245Smarkj	BN_init(&(ctx->RR));
337269245Smarkj	BN_init(&(ctx->N));
338269245Smarkj	BN_init(&(ctx->Ni));
339269245Smarkj	ctx->n0[0] = ctx->n0[1] = 0;
340269245Smarkj	ctx->flags=0;
341269245Smarkj	}
342269245Smarkj
343269245Smarkjvoid BN_MONT_CTX_free(BN_MONT_CTX *mont)
344211554Srpaulo	{
345211554Srpaulo	if(mont == NULL)
346178479Sjb	    return;
347178479Sjb
348211554Srpaulo	BN_free(&(mont->RR));
349178479Sjb	BN_free(&(mont->N));
350211554Srpaulo	BN_free(&(mont->Ni));
351211554Srpaulo	if (mont->flags & BN_FLG_MALLOCED)
352211554Srpaulo		OPENSSL_free(mont);
353211554Srpaulo	}
354178479Sjb
355178479Sjbint BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
356269245Smarkj	{
357211554Srpaulo	int ret = 0;
358269245Smarkj	BIGNUM *Ri,*R;
359269245Smarkj
360269245Smarkj	BN_CTX_start(ctx);
361269245Smarkj	if((Ri = BN_CTX_get(ctx)) == NULL) goto err;
362211554Srpaulo	R= &(mont->RR);					/* grab RR as a temp */
363211554Srpaulo	if (!BN_copy(&(mont->N),mod)) goto err;		/* Set N */
364211554Srpaulo	mont->N.neg = 0;
365178479Sjb
366178479Sjb#ifdef MONT_WORD
367178572Sjb		{
368178479Sjb		BIGNUM tmod;
369178572Sjb		BN_ULONG buf[2];
370178572Sjb
371178572Sjb		BN_init(&tmod);
372178572Sjb		tmod.d=buf;
373178479Sjb		tmod.dmax=2;
374178479Sjb		tmod.neg=0;
375178479Sjb
376178479Sjb		mont->ri=(BN_num_bits(mod)+(BN_BITS2-1))/BN_BITS2*BN_BITS2;
377178479Sjb
378178572Sjb#if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32)
379178572Sjb		/* Only certain BN_BITS2<=32 platforms actually make use of
380178479Sjb		 * n0[1], and we could use the #else case (with a shorter R
381178479Sjb		 * value) for the others.  However, currently only the assembler
382178479Sjb		 * files do know which is which. */
383211554Srpaulo
384178479Sjb		BN_zero(R);
385178479Sjb		if (!(BN_set_bit(R,2*BN_BITS2))) goto err;
386178479Sjb
387178479Sjb								tmod.top=0;
388178479Sjb		if ((buf[0] = mod->d[0]))			tmod.top=1;
389178479Sjb		if ((buf[1] = mod->top>1 ? mod->d[1] : 0))	tmod.top=2;
390
391		if ((BN_mod_inverse(Ri,R,&tmod,ctx)) == NULL)
392			goto err;
393		if (!BN_lshift(Ri,Ri,2*BN_BITS2)) goto err; /* R*Ri */
394		if (!BN_is_zero(Ri))
395			{
396			if (!BN_sub_word(Ri,1)) goto err;
397			}
398		else /* if N mod word size == 1 */
399			{
400			if (bn_expand(Ri,(int)sizeof(BN_ULONG)*2) == NULL)
401				goto err;
402			/* Ri-- (mod double word size) */
403			Ri->neg=0;
404			Ri->d[0]=BN_MASK2;
405			Ri->d[1]=BN_MASK2;
406			Ri->top=2;
407			}
408		if (!BN_div(Ri,NULL,Ri,&tmod,ctx)) goto err;
409		/* Ni = (R*Ri-1)/N,
410		 * keep only couple of least significant words: */
411		mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
412		mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0;
413#else
414		BN_zero(R);
415		if (!(BN_set_bit(R,BN_BITS2))) goto err;	/* R */
416
417		buf[0]=mod->d[0]; /* tmod = N mod word size */
418		buf[1]=0;
419		tmod.top = buf[0] != 0 ? 1 : 0;
420							/* Ri = R^-1 mod N*/
421		if ((BN_mod_inverse(Ri,R,&tmod,ctx)) == NULL)
422			goto err;
423		if (!BN_lshift(Ri,Ri,BN_BITS2)) goto err; /* R*Ri */
424		if (!BN_is_zero(Ri))
425			{
426			if (!BN_sub_word(Ri,1)) goto err;
427			}
428		else /* if N mod word size == 1 */
429			{
430			if (!BN_set_word(Ri,BN_MASK2)) goto err;  /* Ri-- (mod word size) */
431			}
432		if (!BN_div(Ri,NULL,Ri,&tmod,ctx)) goto err;
433		/* Ni = (R*Ri-1)/N,
434		 * keep only least significant word: */
435		mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
436		mont->n0[1] = 0;
437#endif
438		}
439#else /* !MONT_WORD */
440		{ /* bignum version */
441		mont->ri=BN_num_bits(&mont->N);
442		BN_zero(R);
443		if (!BN_set_bit(R,mont->ri)) goto err;  /* R = 2^ri */
444		                                        /* Ri = R^-1 mod N*/
445		if ((BN_mod_inverse(Ri,R,&mont->N,ctx)) == NULL)
446			goto err;
447		if (!BN_lshift(Ri,Ri,mont->ri)) goto err; /* R*Ri */
448		if (!BN_sub_word(Ri,1)) goto err;
449							/* Ni = (R*Ri-1) / N */
450		if (!BN_div(&(mont->Ni),NULL,Ri,&mont->N,ctx)) goto err;
451		}
452#endif
453
454	/* setup RR for conversions */
455	BN_zero(&(mont->RR));
456	if (!BN_set_bit(&(mont->RR),mont->ri*2)) goto err;
457	if (!BN_mod(&(mont->RR),&(mont->RR),&(mont->N),ctx)) goto err;
458
459	ret = 1;
460err:
461	BN_CTX_end(ctx);
462	return ret;
463	}
464
465BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from)
466	{
467	if (to == from) return(to);
468
469	if (!BN_copy(&(to->RR),&(from->RR))) return NULL;
470	if (!BN_copy(&(to->N),&(from->N))) return NULL;
471	if (!BN_copy(&(to->Ni),&(from->Ni))) return NULL;
472	to->ri=from->ri;
473	to->n0[0]=from->n0[0];
474	to->n0[1]=from->n0[1];
475	return(to);
476	}
477
478BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, int lock,
479					const BIGNUM *mod, BN_CTX *ctx)
480	{
481	BN_MONT_CTX *ret;
482
483	CRYPTO_r_lock(lock);
484	ret = *pmont;
485	CRYPTO_r_unlock(lock);
486	if (ret)
487		return ret;
488
489	/* We don't want to serialise globally while doing our lazy-init math in
490	 * BN_MONT_CTX_set. That punishes threads that are doing independent
491	 * things. Instead, punish the case where more than one thread tries to
492	 * lazy-init the same 'pmont', by having each do the lazy-init math work
493	 * independently and only use the one from the thread that wins the race
494	 * (the losers throw away the work they've done). */
495	ret = BN_MONT_CTX_new();
496	if (!ret)
497		return NULL;
498	if (!BN_MONT_CTX_set(ret, mod, ctx))
499		{
500		BN_MONT_CTX_free(ret);
501		return NULL;
502		}
503
504	/* The locked compare-and-set, after the local work is done. */
505	CRYPTO_w_lock(lock);
506	if (*pmont)
507		{
508		BN_MONT_CTX_free(ret);
509		ret = *pmont;
510		}
511	else
512		*pmont = ret;
513	CRYPTO_w_unlock(lock);
514	return ret;
515	}
516