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