mark all block comments that need format preserving so that
[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
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         /*-
267          * From  B = a mod |n|,  A = |n|  it follows that
268          *
269          *      0 <= B < A,
270          *     -sign*X*a  ==  B   (mod |n|),
271          *      sign*Y*a  ==  A   (mod |n|).
272          */
273
274         if (BN_is_odd(n) && (BN_num_bits(n) <= (BN_BITS <= 32 ? 450 : 2048)))
275                 {
276                 /* Binary inversion algorithm; requires odd modulus.
277                  * This is faster than the general algorithm if the modulus
278                  * is sufficiently small (about 400 .. 500 bits on 32-bit
279                  * sytems, but much more on 64-bit systems) */
280                 int shift;
281                 
282                 while (!BN_is_zero(B))
283                         {
284                         /*-
285                          *      0 < B < |n|,
286                          *      0 < A <= |n|,
287                          * (1) -sign*X*a  ==  B   (mod |n|),
288                          * (2)  sign*Y*a  ==  A   (mod |n|)
289                          */
290
291                         /* Now divide  B  by the maximum possible power of two in the integers,
292                          * and divide  X  by the same value mod |n|.
293                          * When we're done, (1) still holds. */
294                         shift = 0;
295                         while (!BN_is_bit_set(B, shift)) /* note that 0 < B */
296                                 {
297                                 shift++;
298                                 
299                                 if (BN_is_odd(X))
300                                         {
301                                         if (!BN_uadd(X, X, n)) goto err;
302                                         }
303                                 /* now X is even, so we can easily divide it by two */
304                                 if (!BN_rshift1(X, X)) goto err;
305                                 }
306                         if (shift > 0)
307                                 {
308                                 if (!BN_rshift(B, B, shift)) goto err;
309                                 }
310
311
312                         /* Same for  A  and  Y.  Afterwards, (2) still holds. */
313                         shift = 0;
314                         while (!BN_is_bit_set(A, shift)) /* note that 0 < A */
315                                 {
316                                 shift++;
317                                 
318                                 if (BN_is_odd(Y))
319                                         {
320                                         if (!BN_uadd(Y, Y, n)) goto err;
321                                         }
322                                 /* now Y is even */
323                                 if (!BN_rshift1(Y, Y)) goto err;
324                                 }
325                         if (shift > 0)
326                                 {
327                                 if (!BN_rshift(A, A, shift)) goto err;
328                                 }
329
330                         
331                         /*-
332                          * We still have (1) and (2).
333                          * Both  A  and  B  are odd.
334                          * The following computations ensure that
335                          *
336                          *     0 <= B < |n|,
337                          *      0 < A < |n|,
338                          * (1) -sign*X*a  ==  B   (mod |n|),
339                          * (2)  sign*Y*a  ==  A   (mod |n|),
340                          *
341                          * and that either  A  or  B  is even in the next iteration.
342                          */
343                         if (BN_ucmp(B, A) >= 0)
344                                 {
345                                 /* -sign*(X + Y)*a == B - A  (mod |n|) */
346                                 if (!BN_uadd(X, X, Y)) goto err;
347                                 /* NB: we could use BN_mod_add_quick(X, X, Y, n), but that
348                                  * actually makes the algorithm slower */
349                                 if (!BN_usub(B, B, A)) goto err;
350                                 }
351                         else
352                                 {
353                                 /*  sign*(X + Y)*a == A - B  (mod |n|) */
354                                 if (!BN_uadd(Y, Y, X)) goto err;
355                                 /* as above, BN_mod_add_quick(Y, Y, X, n) would slow things down */
356                                 if (!BN_usub(A, A, B)) goto err;
357                                 }
358                         }
359                 }
360         else
361                 {
362                 /* general inversion algorithm */
363
364                 while (!BN_is_zero(B))
365                         {
366                         BIGNUM *tmp;
367                         
368                         /*-
369                          *      0 < B < A,
370                          * (*) -sign*X*a  ==  B   (mod |n|),
371                          *      sign*Y*a  ==  A   (mod |n|)
372                          */
373                         
374                         /* (D, M) := (A/B, A%B) ... */
375                         if (BN_num_bits(A) == BN_num_bits(B))
376                                 {
377                                 if (!BN_one(D)) goto err;
378                                 if (!BN_sub(M,A,B)) goto err;
379                                 }
380                         else if (BN_num_bits(A) == BN_num_bits(B) + 1)
381                                 {
382                                 /* A/B is 1, 2, or 3 */
383                                 if (!BN_lshift1(T,B)) goto err;
384                                 if (BN_ucmp(A,T) < 0)
385                                         {
386                                         /* A < 2*B, so D=1 */
387                                         if (!BN_one(D)) goto err;
388                                         if (!BN_sub(M,A,B)) goto err;
389                                         }
390                                 else
391                                         {
392                                         /* A >= 2*B, so D=2 or D=3 */
393                                         if (!BN_sub(M,A,T)) goto err;
394                                         if (!BN_add(D,T,B)) goto err; /* use D (:= 3*B) as temp */
395                                         if (BN_ucmp(A,D) < 0)
396                                                 {
397                                                 /* A < 3*B, so D=2 */
398                                                 if (!BN_set_word(D,2)) goto err;
399                                                 /* M (= A - 2*B) already has the correct value */
400                                                 }
401                                         else
402                                                 {
403                                                 /* only D=3 remains */
404                                                 if (!BN_set_word(D,3)) goto err;
405                                                 /* currently  M = A - 2*B,  but we need  M = A - 3*B */
406                                                 if (!BN_sub(M,M,B)) goto err;
407                                                 }
408                                         }
409                                 }
410                         else
411                                 {
412                                 if (!BN_div(D,M,A,B,ctx)) goto err;
413                                 }
414                         
415                         /*-
416                          * Now
417                          *      A = D*B + M;
418                          * thus we have
419                          * (**)  sign*Y*a  ==  D*B + M   (mod |n|).
420                          */
421                         
422                         tmp=A; /* keep the BIGNUM object, the value does not matter */
423                         
424                         /* (A, B) := (B, A mod B) ... */
425                         A=B;
426                         B=M;
427                         /* ... so we have  0 <= B < A  again */
428                         
429                         /*-
430                          * Since the former  M  is now  B  and the former  B  is now  A,
431                          * (**) translates into
432                          *       sign*Y*a  ==  D*A + B    (mod |n|),
433                          * i.e.
434                          *       sign*Y*a - D*A  ==  B    (mod |n|).
435                          * Similarly, (*) translates into
436                          *      -sign*X*a  ==  A          (mod |n|).
437                          *
438                          * Thus,
439                          *   sign*Y*a + D*sign*X*a  ==  B  (mod |n|),
440                          * i.e.
441                          *        sign*(Y + D*X)*a  ==  B  (mod |n|).
442                          *
443                          * So if we set  (X, Y, sign) := (Y + D*X, X, -sign),  we arrive back at
444                          *      -sign*X*a  ==  B   (mod |n|),
445                          *       sign*Y*a  ==  A   (mod |n|).
446                          * Note that  X  and  Y  stay non-negative all the time.
447                          */
448                         
449                         /* most of the time D is very small, so we can optimize tmp := D*X+Y */
450                         if (BN_is_one(D))
451                                 {
452                                 if (!BN_add(tmp,X,Y)) goto err;
453                                 }
454                         else
455                                 {
456                                 if (BN_is_word(D,2))
457                                         {
458                                         if (!BN_lshift1(tmp,X)) goto err;
459                                         }
460                                 else if (BN_is_word(D,4))
461                                         {
462                                         if (!BN_lshift(tmp,X,2)) goto err;
463                                         }
464                                 else if (D->top == 1)
465                                         {
466                                         if (!BN_copy(tmp,X)) goto err;
467                                         if (!BN_mul_word(tmp,D->d[0])) goto err;
468                                         }
469                                 else
470                                         {
471                                         if (!BN_mul(tmp,D,X,ctx)) goto err;
472                                         }
473                                 if (!BN_add(tmp,tmp,Y)) goto err;
474                                 }
475                         
476                         M=Y; /* keep the BIGNUM object, the value does not matter */
477                         Y=X;
478                         X=tmp;
479                         sign = -sign;
480                         }
481                 }
482                 
483         /*-
484          * The while loop (Euclid's algorithm) ends when
485          *      A == gcd(a,n);
486          * we have
487          *       sign*Y*a  ==  A  (mod |n|),
488          * where  Y  is non-negative.
489          */
490
491         if (sign < 0)
492                 {
493                 if (!BN_sub(Y,n,Y)) goto err;
494                 }
495         /* Now  Y*a  ==  A  (mod |n|).  */
496         
497
498         if (BN_is_one(A))
499                 {
500                 /* Y*a == 1  (mod |n|) */
501                 if (!Y->neg && BN_ucmp(Y,n) < 0)
502                         {
503                         if (!BN_copy(R,Y)) goto err;
504                         }
505                 else
506                         {
507                         if (!BN_nnmod(R,Y,n,ctx)) goto err;
508                         }
509                 }
510         else
511                 {
512                 if (pnoinv)
513                         *pnoinv = 1;
514                 goto err;
515                 }
516         ret=R;
517 err:
518         if ((ret == NULL) && (in == NULL)) BN_free(R);
519         BN_CTX_end(ctx);
520         bn_check_top(ret);
521         return(ret);
522         }
523
524
525 /* BN_mod_inverse_no_branch is a special version of BN_mod_inverse. 
526  * It does not contain branches that may leak sensitive information.
527  */
528 static BIGNUM *BN_mod_inverse_no_branch(BIGNUM *in,
529         const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx)
530         {
531         BIGNUM *A,*B,*X,*Y,*M,*D,*T,*R=NULL;
532         BIGNUM local_A, local_B;
533         BIGNUM *pA, *pB;
534         BIGNUM *ret=NULL;
535         int sign;
536
537         bn_check_top(a);
538         bn_check_top(n);
539
540         BN_CTX_start(ctx);
541         A = BN_CTX_get(ctx);
542         B = BN_CTX_get(ctx);
543         X = BN_CTX_get(ctx);
544         D = BN_CTX_get(ctx);
545         M = BN_CTX_get(ctx);
546         Y = BN_CTX_get(ctx);
547         T = BN_CTX_get(ctx);
548         if (T == NULL) goto err;
549
550         if (in == NULL)
551                 R=BN_new();
552         else
553                 R=in;
554         if (R == NULL) goto err;
555
556         BN_one(X);
557         BN_zero(Y);
558         if (BN_copy(B,a) == NULL) goto err;
559         if (BN_copy(A,n) == NULL) goto err;
560         A->neg = 0;
561
562         if (B->neg || (BN_ucmp(B, A) >= 0))
563                 {
564                 /* Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
565                  * BN_div_no_branch will be called eventually.
566                  */
567                 pB = &local_B;
568                 BN_with_flags(pB, B, BN_FLG_CONSTTIME); 
569                 if (!BN_nnmod(B, pB, A, ctx)) goto err;
570                 }
571         sign = -1;
572         /*-
573          * From  B = a mod |n|,  A = |n|  it follows that
574          *
575          *      0 <= B < A,
576          *     -sign*X*a  ==  B   (mod |n|),
577          *      sign*Y*a  ==  A   (mod |n|).
578          */
579
580         while (!BN_is_zero(B))
581                 {
582                 BIGNUM *tmp;
583                 
584                 /*-
585                  *      0 < B < A,
586                  * (*) -sign*X*a  ==  B   (mod |n|),
587                  *      sign*Y*a  ==  A   (mod |n|)
588                  */
589
590                 /* Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked,
591                  * BN_div_no_branch will be called eventually.
592                  */
593                 pA = &local_A;
594                 BN_with_flags(pA, A, BN_FLG_CONSTTIME); 
595                 
596                 /* (D, M) := (A/B, A%B) ... */          
597                 if (!BN_div(D,M,pA,B,ctx)) goto err;
598                 
599                 /*-
600                  * Now
601                  *      A = D*B + M;
602                  * thus we have
603                  * (**)  sign*Y*a  ==  D*B + M   (mod |n|).
604                  */
605                 
606                 tmp=A; /* keep the BIGNUM object, the value does not matter */
607                 
608                 /* (A, B) := (B, A mod B) ... */
609                 A=B;
610                 B=M;
611                 /* ... so we have  0 <= B < A  again */
612                 
613                 /*-
614                  * Since the former  M  is now  B  and the former  B  is now  A,
615                  * (**) translates into
616                  *       sign*Y*a  ==  D*A + B    (mod |n|),
617                  * i.e.
618                  *       sign*Y*a - D*A  ==  B    (mod |n|).
619                  * Similarly, (*) translates into
620                  *      -sign*X*a  ==  A          (mod |n|).
621                  *
622                  * Thus,
623                  *   sign*Y*a + D*sign*X*a  ==  B  (mod |n|),
624                  * i.e.
625                  *        sign*(Y + D*X)*a  ==  B  (mod |n|).
626                  *
627                  * So if we set  (X, Y, sign) := (Y + D*X, X, -sign),  we arrive back at
628                  *      -sign*X*a  ==  B   (mod |n|),
629                  *       sign*Y*a  ==  A   (mod |n|).
630                  * Note that  X  and  Y  stay non-negative all the time.
631                  */
632                         
633                 if (!BN_mul(tmp,D,X,ctx)) goto err;
634                 if (!BN_add(tmp,tmp,Y)) goto err;
635
636                 M=Y; /* keep the BIGNUM object, the value does not matter */
637                 Y=X;
638                 X=tmp;
639                 sign = -sign;
640                 }
641                 
642         /*-
643          * The while loop (Euclid's algorithm) ends when
644          *      A == gcd(a,n);
645          * we have
646          *       sign*Y*a  ==  A  (mod |n|),
647          * where  Y  is non-negative.
648          */
649
650         if (sign < 0)
651                 {
652                 if (!BN_sub(Y,n,Y)) goto err;
653                 }
654         /* Now  Y*a  ==  A  (mod |n|).  */
655
656         if (BN_is_one(A))
657                 {
658                 /* Y*a == 1  (mod |n|) */
659                 if (!Y->neg && BN_ucmp(Y,n) < 0)
660                         {
661                         if (!BN_copy(R,Y)) goto err;
662                         }
663                 else
664                         {
665                         if (!BN_nnmod(R,Y,n,ctx)) goto err;
666                         }
667                 }
668         else
669                 {
670                 BNerr(BN_F_BN_MOD_INVERSE_NO_BRANCH,BN_R_NO_INVERSE);
671                 goto err;
672                 }
673         ret=R;
674 err:
675         if ((ret == NULL) && (in == NULL)) BN_free(R);
676         BN_CTX_end(ctx);
677         bn_check_top(ret);
678         return(ret);
679         }