d53f32656b2e84927109a1415030d734d7a30834
[openssl.git] / crypto / bn / bn_gcd.c
1 /* crypto/bn/bn_gcd.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  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include "cryptlib.h"
113 #include "bn_lcl.h"
114
115 static BIGNUM *euclid(BIGNUM *a, BIGNUM *b);
116
117 int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx)
118         {
119         BIGNUM *a,*b,*t;
120         int ret=0;
121
122         bn_check_top(in_a);
123         bn_check_top(in_b);
124
125         BN_CTX_start(ctx);
126         a = BN_CTX_get(ctx);
127         b = BN_CTX_get(ctx);
128         if (a == NULL || b == NULL) goto err;
129
130         if (BN_copy(a,in_a) == NULL) goto err;
131         if (BN_copy(b,in_b) == NULL) goto err;
132         a->neg = 0;
133         b->neg = 0;
134
135         if (BN_cmp(a,b) < 0) { t=a; a=b; b=t; }
136         t=euclid(a,b);
137         if (t == NULL) goto err;
138
139         if (BN_copy(r,t) == NULL) goto err;
140         ret=1;
141 err:
142         BN_CTX_end(ctx);
143         return(ret);
144         }
145
146 static BIGNUM *euclid(BIGNUM *a, BIGNUM *b)
147         {
148         BIGNUM *t;
149         int shifts=0;
150
151         bn_check_top(a);
152         bn_check_top(b);
153
154         /* 0 <= b <= a */
155         while (!BN_is_zero(b))
156                 {
157                 /* 0 < b <= a */
158
159                 if (BN_is_odd(a))
160                         {
161                         if (BN_is_odd(b))
162                                 {
163                                 if (!BN_sub(a,a,b)) goto err;
164                                 if (!BN_rshift1(a,a)) goto err;
165                                 if (BN_cmp(a,b) < 0)
166                                         { t=a; a=b; b=t; }
167                                 }
168                         else            /* a odd - b even */
169                                 {
170                                 if (!BN_rshift1(b,b)) goto err;
171                                 if (BN_cmp(a,b) < 0)
172                                         { t=a; a=b; b=t; }
173                                 }
174                         }
175                 else                    /* a is even */
176                         {
177                         if (BN_is_odd(b))
178                                 {
179                                 if (!BN_rshift1(a,a)) goto err;
180                                 if (BN_cmp(a,b) < 0)
181                                         { t=a; a=b; b=t; }
182                                 }
183                         else            /* a even - b even */
184                                 {
185                                 if (!BN_rshift1(a,a)) goto err;
186                                 if (!BN_rshift1(b,b)) goto err;
187                                 shifts++;
188                                 }
189                         }
190                 /* 0 <= b <= a */
191                 }
192
193         if (shifts)
194                 {
195                 if (!BN_lshift(a,a,shifts)) goto err;
196                 }
197         return(a);
198 err:
199         return(NULL);
200         }
201
202
203 /* solves ax == 1 (mod n) */
204 BIGNUM *BN_mod_inverse(BIGNUM *in,
205         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx)
206         {
207         BIGNUM *A,*B,*X,*Y,*M,*D,*T,*R=NULL;
208         BIGNUM *ret=NULL;
209         int sign;
210
211         bn_check_top(a);
212         bn_check_top(n);
213
214         BN_CTX_start(ctx);
215         A = BN_CTX_get(ctx);
216         B = BN_CTX_get(ctx);
217         X = BN_CTX_get(ctx);
218         D = BN_CTX_get(ctx);
219         M = BN_CTX_get(ctx);
220         Y = BN_CTX_get(ctx);
221         T = BN_CTX_get(ctx);
222         if (T == NULL) goto err;
223
224         if (in == NULL)
225                 R=BN_new();
226         else
227                 R=in;
228         if (R == NULL) goto err;
229
230         BN_one(X);
231         BN_zero(Y);
232         if (BN_copy(B,a) == NULL) goto err;
233         if (BN_copy(A,n) == NULL) goto err;
234         A->neg = 0;
235         if (B->neg || (BN_ucmp(B, A) >= 0))
236                 {
237                 if (!BN_nnmod(B, B, A, ctx)) goto err;
238                 }
239         sign = -1;
240         /* From  B = a mod |n|,  A = |n|  it follows that
241          *
242          *      0 <= B < A,
243          *           X*a  ==  B   (mod |n|),
244          *     -sign*Y*a  ==  A   (mod |n|).
245          */
246
247         while (!BN_is_zero(B))
248                 {
249                 BIGNUM *tmp;
250
251                 /*
252                  *      0 < B < A,
253                  * (*)       X*a  ==  B   (mod |n|),
254                  *     -sign*Y*a  ==  A   (mod |n|)
255                  */
256
257                 /* (D, M) := (A/B, A%B) ... */
258                 if (BN_num_bits(A) == BN_num_bits(B))
259                         {
260                         if (!BN_one(D)) goto err;
261                         if (!BN_sub(M,A,B)) goto err;
262                         }
263                 else if (BN_num_bits(A) == BN_num_bits(B) + 1)
264                         {
265                         /* A/B is 1, 2, or 3 */
266                         if (!BN_lshift1(T,B)) goto err;
267                         if (BN_ucmp(A,T) < 0)
268                                 {
269                                 /* A < 2*B, so D=1 */
270                                 if (!BN_one(D)) goto err;
271                                 if (!BN_sub(M,A,B)) goto err;
272                                 }
273                         else
274                                 {
275                                 /* A >= 2*B, so D=2 or D=3 */
276                                 if (!BN_sub(M,A,T)) goto err;
277                                 if (!BN_add(D,T,B)) goto err; /* use D (:= 3*B) as temp */
278                                 if (BN_ucmp(A,D) < 0)
279                                         {
280                                         /* A < 3*B, so D=2 */
281                                         if (!BN_set_word(D,2)) goto err;
282                                         /* M (= A - 2*B) already has the correct value */
283                                         }
284                                 else
285                                         {
286                                         /* only D=3 remains */
287                                         if (!BN_set_word(D,3)) goto err;
288                                         /* currently  M = A - 2*B,  but we need  M = A - 3*B */
289                                         if (!BN_sub(M,M,B)) goto err;
290                                         }
291                                 }
292                         }
293                 else
294                         {
295                         if (!BN_div(D,M,A,B,ctx)) goto err;
296                         }
297                 
298                 /* Now
299                  *      A = D*B + M;
300                  * thus we have
301                  * (**) -sign*Y*a  ==  D*B + M   (mod |n|).
302                  */
303                 
304                 tmp=A; /* keep the BIGNUM object, the value does not matter */
305
306                 /* (A, B) := (B, A mod B) ... */
307                 A=B;
308                 B=M;
309                 /* ... so we have  0 <= B < A  again */
310
311                 /* Since the former  M  is now  B  and the former  B  is now  A,
312                  * (**) translates into
313                  *      -sign*Y*a  ==  D*A + B    (mod |n|),
314                  * i.e.
315                  *      -sign*Y*a - D*A  ==  B    (mod |n|).
316                  * Similarly, (*) translates into
317                  *      X*a  ==  A          (mod |n|).
318                  *
319                  * Thus,
320                  *      -sign*Y*a - D*X*a  ==  B  (mod |n|),
321                  * i.e.
322                  *      -sign*(Y + D*X)*a  ==  B  (mod |n|).
323                  *
324                  * So if we set  (X, Y, sign) := (Y + D*X, X, -sign),  we arrive back at
325                  *            X*a  ==  B   (mod |n|),
326                  *      -sign*Y*a  ==  A   (mod |n|).
327                  * Note that  X  and  Y  stay non-negative all the time.
328                  */
329
330                 /* most of the time D is very small, so we can optimize tmp := D*X+Y */
331                 if (BN_is_one(D))
332                         {
333                         if (!BN_add(tmp,X,Y)) goto err;
334                         }
335                 else
336                         {
337                         if (BN_is_word(D,2))
338                                 {
339                                 if (!BN_lshift1(tmp,X)) goto err;
340                                 }
341                         else if (BN_is_word(D,3))
342                                 {
343                                 if (!BN_lshift1(tmp,X)) goto err;
344                                 if (!BN_add(tmp,tmp,X)) goto err;
345                                 }
346                         else if (BN_is_word(D,4))
347                                 {
348                                 if (!BN_lshift(tmp,X,2)) goto err;
349                                 }
350                         else
351                                 {
352                                 if (!BN_mul(tmp,D,X,ctx)) goto err;
353                                 }
354                         if (!BN_add(tmp,tmp,Y)) goto err;
355                         }
356                 
357                 M=Y; /* keep the BIGNUM object, the value does not matter */
358                 Y=X;
359                 X=tmp;
360                 sign = -sign;
361                 }
362
363         /*
364          * The while loop ends when
365          *      A == gcd(a,n);
366          * we have
367          *      -sign*Y*a  ==  A  (mod |n|),
368          * where  Y  is non-negative.
369          */
370
371         if (sign < 0)
372                 {
373                 if (!BN_sub(Y,n,Y)) goto err;
374                 }
375         /* Now  Y*a  ==  A  (mod |n|).  */
376         
377
378         if (BN_is_one(A))
379                 {
380                 /* Y*a == 1  (mod |n|) */
381                 if (BN_ucmp(Y,n) < 0)
382                         if (!BN_copy(R,Y)) goto err;
383                 else
384                         if (!BN_nnmod(R,Y,n,ctx)) goto err;
385                 }
386         else
387                 {
388                 BNerr(BN_F_BN_MOD_INVERSE,BN_R_NO_INVERSE);
389                 goto err;
390                 }
391         ret=R;
392 err:
393         if ((ret == NULL) && (in == NULL)) BN_free(R);
394         BN_CTX_end(ctx);
395         return(ret);
396         }
397