bn_word.c: fix overflow bug in BN_add_word.
[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-2001 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 #define OPENSSL_FIPSAPI
113
114 #include "cryptlib.h"
115 #include "bn_lcl.h"
116
117 static BIGNUM *euclid(BIGNUM *a, BIGNUM *b);
118
119 int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx)
120         {
121         BIGNUM *a,*b,*t;
122         int ret=0;
123
124         bn_check_top(in_a);
125         bn_check_top(in_b);
126
127         BN_CTX_start(ctx);
128         a = BN_CTX_get(ctx);
129         b = BN_CTX_get(ctx);
130         if (a == NULL || b == NULL) goto err;
131
132         if (BN_copy(a,in_a) == NULL) goto err;
133         if (BN_copy(b,in_b) == NULL) goto err;
134         a->neg = 0;
135         b->neg = 0;
136
137         if (BN_cmp(a,b) < 0) { t=a; a=b; b=t; }
138         t=euclid(a,b);
139         if (t == NULL) goto err;
140
141         if (BN_copy(r,t) == NULL) goto err;
142         ret=1;
143 err:
144         BN_CTX_end(ctx);
145         bn_check_top(r);
146         return(ret);
147         }
148
149 static BIGNUM *euclid(BIGNUM *a, BIGNUM *b)
150         {
151         BIGNUM *t;
152         int shifts=0;
153
154         bn_check_top(a);
155         bn_check_top(b);
156
157         /* 0 <= b <= a */
158         while (!BN_is_zero(b))
159                 {
160                 /* 0 < b <= a */
161
162                 if (BN_is_odd(a))
163                         {
164                         if (BN_is_odd(b))
165                                 {
166                                 if (!BN_sub(a,a,b)) goto err;
167                                 if (!BN_rshift1(a,a)) goto err;
168                                 if (BN_cmp(a,b) < 0)
169                                         { t=a; a=b; b=t; }
170                                 }
171                         else            /* a odd - b even */
172                                 {
173                                 if (!BN_rshift1(b,b)) goto err;
174                                 if (BN_cmp(a,b) < 0)
175                                         { t=a; a=b; b=t; }
176                                 }
177                         }
178                 else                    /* a is even */
179                         {
180                         if (BN_is_odd(b))
181                                 {
182                                 if (!BN_rshift1(a,a)) goto err;
183                                 if (BN_cmp(a,b) < 0)
184                                         { t=a; a=b; b=t; }
185                                 }
186                         else            /* a even - b even */
187                                 {
188                                 if (!BN_rshift1(a,a)) goto err;
189                                 if (!BN_rshift1(b,b)) goto err;
190                                 shifts++;
191                                 }
192                         }
193                 /* 0 <= b <= a */
194                 }
195
196         if (shifts)
197                 {
198                 if (!BN_lshift(a,a,shifts)) goto err;
199                 }
200         bn_check_top(a);
201         return(a);
202 err:
203         return(NULL);
204         }
205
206
207 /* solves ax == 1 (mod n) */
208 static BIGNUM *BN_mod_inverse_no_branch(BIGNUM *in,
209         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
210
211 BIGNUM *BN_mod_inverse(BIGNUM *in,
212         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx)
213         {
214         BIGNUM *rv;
215         int noinv;
216         rv = int_bn_mod_inverse(in, a, n, ctx, &noinv);
217         if (noinv)
218                 BNerr(BN_F_BN_MOD_INVERSE,BN_R_NO_INVERSE);
219         return rv;
220         }
221
222 BIGNUM *int_bn_mod_inverse(BIGNUM *in,
223         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *pnoinv)
224         {
225         BIGNUM *A,*B,*X,*Y,*M,*D,*T,*R=NULL;
226         BIGNUM *ret=NULL;
227         int sign;
228
229         if (pnoinv)
230                 *pnoinv = 0;
231
232         if ((BN_get_flags(a, BN_FLG_CONSTTIME) != 0) || (BN_get_flags(n, BN_FLG_CONSTTIME) != 0))
233                 {
234                 return BN_mod_inverse_no_branch(in, a, n, ctx);
235                 }
236
237         bn_check_top(a);
238         bn_check_top(n);
239
240         BN_CTX_start(ctx);
241         A = BN_CTX_get(ctx);
242         B = BN_CTX_get(ctx);
243         X = BN_CTX_get(ctx);
244         D = BN_CTX_get(ctx);
245         M = BN_CTX_get(ctx);
246         Y = BN_CTX_get(ctx);
247         T = BN_CTX_get(ctx);
248         if (T == NULL) goto err;
249
250         if (in == NULL)
251                 R=BN_new();
252         else
253                 R=in;
254         if (R == NULL) goto err;
255
256         BN_one(X);
257         BN_zero(Y);
258         if (BN_copy(B,a) == NULL) goto err;
259         if (BN_copy(A,n) == NULL) goto err;
260         A->neg = 0;
261         if (B->neg || (BN_ucmp(B, A) >= 0))
262                 {
263                 if (!BN_nnmod(B, B, A, ctx)) goto err;
264                 }
265         sign = -1;
266         /* From  B = a mod |n|,  A = |n|  it follows that
267          *
268          *      0 <= B < A,
269          *     -sign*X*a  ==  B   (mod |n|),
270          *      sign*Y*a  ==  A   (mod |n|).
271          */
272
273         if (BN_is_odd(n) && (BN_num_bits(n) <= (BN_BITS <= 32 ? 450 : 2048)))
274                 {
275                 /* Binary inversion algorithm; requires odd modulus.
276                  * This is faster than the general algorithm if the modulus
277                  * is sufficiently small (about 400 .. 500 bits on 32-bit
278                  * sytems, but much more on 64-bit systems) */
279                 int shift;
280                 
281                 while (!BN_is_zero(B))
282                         {
283                         /*
284                          *      0 < B < |n|,
285                          *      0 < A <= |n|,
286                          * (1) -sign*X*a  ==  B   (mod |n|),
287                          * (2)  sign*Y*a  ==  A   (mod |n|)
288                          */
289
290                         /* Now divide  B  by the maximum possible power of two in the integers,
291                          * and divide  X  by the same value mod |n|.
292                          * When we're done, (1) still holds. */
293                         shift = 0;
294                         while (!BN_is_bit_set(B, shift)) /* note that 0 < B */
295                                 {
296                                 shift++;
297                                 
298                                 if (BN_is_odd(X))
299                                         {
300                                         if (!BN_uadd(X, X, n)) goto err;
301                                         }
302                                 /* now X is even, so we can easily divide it by two */
303                                 if (!BN_rshift1(X, X)) goto err;
304                                 }
305                         if (shift > 0)
306                                 {
307                                 if (!BN_rshift(B, B, shift)) goto err;
308                                 }
309
310
311                         /* Same for  A  and  Y.  Afterwards, (2) still holds. */
312                         shift = 0;
313                         while (!BN_is_bit_set(A, shift)) /* note that 0 < A */
314                                 {
315                                 shift++;
316                                 
317                                 if (BN_is_odd(Y))
318                                         {
319                                         if (!BN_uadd(Y, Y, n)) goto err;
320                                         }
321                                 /* now Y is even */
322                                 if (!BN_rshift1(Y, Y)) goto err;
323                                 }
324                         if (shift > 0)
325                                 {
326                                 if (!BN_rshift(A, A, shift)) goto err;
327                                 }
328
329                         
330                         /* We still have (1) and (2).
331                          * Both  A  and  B  are odd.
332                          * The following computations ensure that
333                          *
334                          *     0 <= B < |n|,
335                          *      0 < A < |n|,
336                          * (1) -sign*X*a  ==  B   (mod |n|),
337                          * (2)  sign*Y*a  ==  A   (mod |n|),
338                          *
339                          * and that either  A  or  B  is even in the next iteration.
340                          */
341                         if (BN_ucmp(B, A) >= 0)
342                                 {
343                                 /* -sign*(X + Y)*a == B - A  (mod |n|) */
344                                 if (!BN_uadd(X, X, Y)) goto err;
345                                 /* NB: we could use BN_mod_add_quick(X, X, Y, n), but that
346                                  * actually makes the algorithm slower */
347                                 if (!BN_usub(B, B, A)) goto err;
348                                 }
349                         else
350                                 {
351                                 /*  sign*(X + Y)*a == A - B  (mod |n|) */
352                                 if (!BN_uadd(Y, Y, X)) goto err;
353                                 /* as above, BN_mod_add_quick(Y, Y, X, n) would slow things down */
354                                 if (!BN_usub(A, A, B)) goto err;
355                                 }
356                         }
357                 }
358         else
359                 {
360                 /* general inversion algorithm */
361
362                 while (!BN_is_zero(B))
363                         {
364                         BIGNUM *tmp;
365                         
366                         /*
367                          *      0 < B < A,
368                          * (*) -sign*X*a  ==  B   (mod |n|),
369                          *      sign*Y*a  ==  A   (mod |n|)
370                          */
371                         
372                         /* (D, M) := (A/B, A%B) ... */
373                         if (BN_num_bits(A) == BN_num_bits(B))
374                                 {
375                                 if (!BN_one(D)) goto err;
376                                 if (!BN_sub(M,A,B)) goto err;
377                                 }
378                         else if (BN_num_bits(A) == BN_num_bits(B) + 1)
379                                 {
380                                 /* A/B is 1, 2, or 3 */
381                                 if (!BN_lshift1(T,B)) goto err;
382                                 if (BN_ucmp(A,T) < 0)
383                                         {
384                                         /* A < 2*B, so D=1 */
385                                         if (!BN_one(D)) goto err;
386                                         if (!BN_sub(M,A,B)) goto err;
387                                         }
388                                 else
389                                         {
390                                         /* A >= 2*B, so D=2 or D=3 */
391                                         if (!BN_sub(M,A,T)) goto err;
392                                         if (!BN_add(D,T,B)) goto err; /* use D (:= 3*B) as temp */
393                                         if (BN_ucmp(A,D) < 0)
394                                                 {
395                                                 /* A < 3*B, so D=2 */
396                                                 if (!BN_set_word(D,2)) goto err;
397                                                 /* M (= A - 2*B) already has the correct value */
398                                                 }
399                                         else
400                                                 {
401                                                 /* only D=3 remains */
402                                                 if (!BN_set_word(D,3)) goto err;
403                                                 /* currently  M = A - 2*B,  but we need  M = A - 3*B */
404                                                 if (!BN_sub(M,M,B)) goto err;
405                                                 }
406                                         }
407                                 }
408                         else
409                                 {
410                                 if (!BN_div(D,M,A,B,ctx)) goto err;
411                                 }
412                         
413                         /* Now
414                          *      A = D*B + M;
415                          * thus we have
416                          * (**)  sign*Y*a  ==  D*B + M   (mod |n|).
417                          */
418                         
419                         tmp=A; /* keep the BIGNUM object, the value does not matter */
420                         
421                         /* (A, B) := (B, A mod B) ... */
422                         A=B;
423                         B=M;
424                         /* ... so we have  0 <= B < A  again */
425                         
426                         /* Since the former  M  is now  B  and the former  B  is now  A,
427                          * (**) translates into
428                          *       sign*Y*a  ==  D*A + B    (mod |n|),
429                          * i.e.
430                          *       sign*Y*a - D*A  ==  B    (mod |n|).
431                          * Similarly, (*) translates into
432                          *      -sign*X*a  ==  A          (mod |n|).
433                          *
434                          * Thus,
435                          *   sign*Y*a + D*sign*X*a  ==  B  (mod |n|),
436                          * i.e.
437                          *        sign*(Y + D*X)*a  ==  B  (mod |n|).
438                          *
439                          * So if we set  (X, Y, sign) := (Y + D*X, X, -sign),  we arrive back at
440                          *      -sign*X*a  ==  B   (mod |n|),
441                          *       sign*Y*a  ==  A   (mod |n|).
442                          * Note that  X  and  Y  stay non-negative all the time.
443                          */
444                         
445                         /* most of the time D is very small, so we can optimize tmp := D*X+Y */
446                         if (BN_is_one(D))
447                                 {
448                                 if (!BN_add(tmp,X,Y)) goto err;
449                                 }
450                         else
451                                 {
452                                 if (BN_is_word(D,2))
453                                         {
454                                         if (!BN_lshift1(tmp,X)) goto err;
455                                         }
456                                 else if (BN_is_word(D,4))
457                                         {
458                                         if (!BN_lshift(tmp,X,2)) goto err;
459                                         }
460                                 else if (D->top == 1)
461                                         {
462                                         if (!BN_copy(tmp,X)) goto err;
463                                         if (!BN_mul_word(tmp,D->d[0])) goto err;
464                                         }
465                                 else
466                                         {
467                                         if (!BN_mul(tmp,D,X,ctx)) goto err;
468                                         }
469                                 if (!BN_add(tmp,tmp,Y)) goto err;
470                                 }
471                         
472                         M=Y; /* keep the BIGNUM object, the value does not matter */
473                         Y=X;
474                         X=tmp;
475                         sign = -sign;
476                         }
477                 }
478                 
479         /*
480          * The while loop (Euclid's algorithm) ends when
481          *      A == gcd(a,n);
482          * we have
483          *       sign*Y*a  ==  A  (mod |n|),
484          * where  Y  is non-negative.
485          */
486
487         if (sign < 0)
488                 {
489                 if (!BN_sub(Y,n,Y)) goto err;
490                 }
491         /* Now  Y*a  ==  A  (mod |n|).  */
492         
493
494         if (BN_is_one(A))
495                 {
496                 /* Y*a == 1  (mod |n|) */
497                 if (!Y->neg && BN_ucmp(Y,n) < 0)
498                         {
499                         if (!BN_copy(R,Y)) goto err;
500                         }
501                 else
502                         {
503                         if (!BN_nnmod(R,Y,n,ctx)) goto err;
504                         }
505                 }
506         else
507                 {
508                 if (pnoinv)
509                         *pnoinv = 1;
510                 goto err;
511                 }
512         ret=R;
513 err:
514         if ((ret == NULL) && (in == NULL)) BN_free(R);
515         BN_CTX_end(ctx);
516         bn_check_top(ret);
517         return(ret);
518         }
519
520
521 /* BN_mod_inverse_no_branch is a special version of BN_mod_inverse. 
522  * It does not contain branches that may leak sensitive information.
523  */
524 static BIGNUM *BN_mod_inverse_no_branch(BIGNUM *in,
525         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx)
526         {
527         BIGNUM *A,*B,*X,*Y,*M,*D,*T,*R=NULL;
528         BIGNUM local_A, local_B;
529         BIGNUM *pA, *pB;
530         BIGNUM *ret=NULL;
531         int sign;
532
533         bn_check_top(a);
534         bn_check_top(n);
535
536         BN_CTX_start(ctx);
537         A = BN_CTX_get(ctx);
538         B = BN_CTX_get(ctx);
539         X = BN_CTX_get(ctx);
540         D = BN_CTX_get(ctx);
541         M = BN_CTX_get(ctx);
542         Y = BN_CTX_get(ctx);
543         T = BN_CTX_get(ctx);
544         if (T == NULL) goto err;
545
546         if (in == NULL)
547                 R=BN_new();
548         else
549                 R=in;
550         if (R == NULL) goto err;
551
552         BN_one(X);
553         BN_zero(Y);
554         if (BN_copy(B,a) == NULL) goto err;
555         if (BN_copy(A,n) == NULL) goto err;
556         A->neg = 0;
557
558         if (B->neg || (BN_ucmp(B, A) >= 0))
559                 {
560                 /* Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
561                  * BN_div_no_branch will be called eventually.
562                  */
563                 pB = &local_B;
564                 BN_with_flags(pB, B, BN_FLG_CONSTTIME); 
565                 if (!BN_nnmod(B, pB, A, ctx)) goto err;
566                 }
567         sign = -1;
568         /* From  B = a mod |n|,  A = |n|  it follows that
569          *
570          *      0 <= B < A,
571          *     -sign*X*a  ==  B   (mod |n|),
572          *      sign*Y*a  ==  A   (mod |n|).
573          */
574
575         while (!BN_is_zero(B))
576                 {
577                 BIGNUM *tmp;
578                 
579                 /*
580                  *      0 < B < A,
581                  * (*) -sign*X*a  ==  B   (mod |n|),
582                  *      sign*Y*a  ==  A   (mod |n|)
583                  */
584
585                 /* Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
586                  * BN_div_no_branch will be called eventually.
587                  */
588                 pA = &local_A;
589                 BN_with_flags(pA, A, BN_FLG_CONSTTIME); 
590                 
591                 /* (D, M) := (A/B, A%B) ... */          
592                 if (!BN_div(D,M,pA,B,ctx)) goto err;
593                 
594                 /* Now
595                  *      A = D*B + M;
596                  * thus we have
597                  * (**)  sign*Y*a  ==  D*B + M   (mod |n|).
598                  */
599                 
600                 tmp=A; /* keep the BIGNUM object, the value does not matter */
601                 
602                 /* (A, B) := (B, A mod B) ... */
603                 A=B;
604                 B=M;
605                 /* ... so we have  0 <= B < A  again */
606                 
607                 /* Since the former  M  is now  B  and the former  B  is now  A,
608                  * (**) translates into
609                  *       sign*Y*a  ==  D*A + B    (mod |n|),
610                  * i.e.
611                  *       sign*Y*a - D*A  ==  B    (mod |n|).
612                  * Similarly, (*) translates into
613                  *      -sign*X*a  ==  A          (mod |n|).
614                  *
615                  * Thus,
616                  *   sign*Y*a + D*sign*X*a  ==  B  (mod |n|),
617                  * i.e.
618                  *        sign*(Y + D*X)*a  ==  B  (mod |n|).
619                  *
620                  * So if we set  (X, Y, sign) := (Y + D*X, X, -sign),  we arrive back at
621                  *      -sign*X*a  ==  B   (mod |n|),
622                  *       sign*Y*a  ==  A   (mod |n|).
623                  * Note that  X  and  Y  stay non-negative all the time.
624                  */
625                         
626                 if (!BN_mul(tmp,D,X,ctx)) goto err;
627                 if (!BN_add(tmp,tmp,Y)) goto err;
628
629                 M=Y; /* keep the BIGNUM object, the value does not matter */
630                 Y=X;
631                 X=tmp;
632                 sign = -sign;
633                 }
634                 
635         /*
636          * The while loop (Euclid's algorithm) ends when
637          *      A == gcd(a,n);
638          * we have
639          *       sign*Y*a  ==  A  (mod |n|),
640          * where  Y  is non-negative.
641          */
642
643         if (sign < 0)
644                 {
645                 if (!BN_sub(Y,n,Y)) goto err;
646                 }
647         /* Now  Y*a  ==  A  (mod |n|).  */
648
649         if (BN_is_one(A))
650                 {
651                 /* Y*a == 1  (mod |n|) */
652                 if (!Y->neg && BN_ucmp(Y,n) < 0)
653                         {
654                         if (!BN_copy(R,Y)) goto err;
655                         }
656                 else
657                         {
658                         if (!BN_nnmod(R,Y,n,ctx)) goto err;
659                         }
660                 }
661         else
662                 {
663                 BNerr(BN_F_BN_MOD_INVERSE_NO_BRANCH,BN_R_NO_INVERSE);
664                 goto err;
665                 }
666         ret=R;
667 err:
668         if ((ret == NULL) && (in == NULL)) BN_free(R);
669         BN_CTX_end(ctx);
670         bn_check_top(ret);
671         return(ret);
672         }