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