4 //FIXME Not checked on threadsafety yet; after checking please remove this line
5 /* crypto/bn/bn_exp.c */
6 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
9 * This package is an SSL implementation written
10 * by Eric Young (eay@cryptsoft.com).
11 * The implementation was written so as to conform with Netscapes SSL.
13 * This library is free for commercial and non-commercial use as long as
14 * the following conditions are aheared to. The following conditions
15 * apply to all code found in this distribution, be it the RC4, RSA,
16 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
17 * included with this distribution is covered by the same copyright terms
18 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
20 * Copyright remains Eric Young's, and as such any Copyright notices in
21 * the code are not to be removed.
22 * If this package is used in a product, Eric Young should be given attribution
23 * as the author of the parts of the library used.
24 * This can be in the form of a textual message at program startup or
25 * in documentation (online or textual) provided with the package.
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
30 * 1. Redistributions of source code must retain the copyright
31 * notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 * notice, this list of conditions and the following disclaimer in the
34 * documentation and/or other materials provided with the distribution.
35 * 3. All advertising materials mentioning features or use of this software
36 * must display the following acknowledgement:
37 * "This product includes cryptographic software written by
38 * Eric Young (eay@cryptsoft.com)"
39 * The word 'cryptographic' can be left out if the rouines from the library
40 * being used are not cryptographic related :-).
41 * 4. If you include any Windows specific code (or a derivative thereof) from
42 * the apps directory (application code) you must include an acknowledgement:
43 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
45 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * The license and distribution terms for any publically available version or
58 * derivative of this code cannot be changed. i.e. this code cannot simply be
59 * copied and put under another distribution license
60 * [including the GNU Public License.]
62 /* ====================================================================
63 * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
69 * 1. Redistributions of source code must retain the above copyright
70 * notice, this list of conditions and the following disclaimer.
72 * 2. Redistributions in binary form must reproduce the above copyright
73 * notice, this list of conditions and the following disclaimer in
74 * the documentation and/or other materials provided with the
77 * 3. All advertising materials mentioning features or use of this
78 * software must display the following acknowledgment:
79 * "This product includes software developed by the OpenSSL Project
80 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
82 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
83 * endorse or promote products derived from this software without
84 * prior written permission. For written permission, please contact
85 * openssl-core@openssl.org.
87 * 5. Products derived from this software may not be called "OpenSSL"
88 * nor may "OpenSSL" appear in their names without prior written
89 * permission of the OpenSSL Project.
91 * 6. Redistributions of any form whatsoever must retain the following
93 * "This product includes software developed by the OpenSSL Project
94 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
96 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
97 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
99 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
100 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
101 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
102 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
103 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
104 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
105 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
107 * OF THE POSSIBILITY OF SUCH DAMAGE.
108 * ====================================================================
110 * This product includes cryptographic software written by Eric Young
111 * (eay@cryptsoft.com). This product includes software written by Tim
112 * Hudson (tjh@cryptsoft.com).
120 #define TABLE_SIZE 32
123 int BN_mod_mul(BIGNUM
*ret
, BIGNUM
*a
, BIGNUM
*b
, const BIGNUM
*m
, BN_CTX
*ctx
)
133 if((t
= BN_CTX_get(ctx
)) == NULL
) { goto err
; }
136 if(!BN_sqr(t
, a
, ctx
)) { goto err
; }
140 if(!BN_mul(t
, a
, b
, ctx
)) { goto err
; }
142 if(!BN_mod(ret
, t
, m
, ctx
)) { goto err
; }
150 int BN_mod_exp(BIGNUM
*r
, BIGNUM
*a
, const BIGNUM
*p
, const BIGNUM
*m
,
159 ret
= BN_mod_exp_simple(r
, a
, p
, m
, ctx
);
168 /* The old fallback, simple version :-) */
169 int BN_mod_exp_simple(BIGNUM
*r
, BIGNUM
*a
, const BIGNUM
*p
, const BIGNUM
*m
,
172 int i
, j
= 0, bits
, ret
= 0, wstart
= 0, wend
= 0, window
, wvalue
= 0, ts
= 0;
175 BIGNUM val
[TABLE_SIZE
];
177 bits
= BN_num_bits(p
);
186 if((d
= BN_CTX_get(ctx
)) == NULL
) { goto err
; }
190 if(!BN_mod(&(val
[0]), a
, m
, ctx
)) { goto err
; } /* 1 */
192 window
= BN_window_bits_for_exponent_size(bits
);
195 if(!BN_mod_mul(d
, &(val
[0]), &(val
[0]), m
, ctx
))
196 { goto err
; } /* 2 */
197 j
= 1 << (window
- 1);
198 for(i
= 1; i
< j
; i
++)
201 if(!BN_mod_mul(&(val
[i
]), &(val
[i
- 1]), d
, m
, ctx
))
207 start
= 1; /* This is used to avoid multiplication etc
208 * when there is only the value '1' in the
210 wstart
= bits
- 1; /* The top bit of the window */
212 if(!BN_one(r
)) { goto err
; }
216 if(BN_is_bit_set(p
, wstart
) == 0)
219 if(!BN_mod_mul(r
, r
, r
, m
, ctx
))
221 if(wstart
== 0) { break; }
225 /* We now have wstart on a 'set' bit, we now need to work out
226 * how bit a window to do. To do this we need to scan
227 * forward until the last set bit before the end of the
232 for(i
= 1; i
< window
; i
++)
234 if(wstart
- i
< 0) { break; }
235 if(BN_is_bit_set(p
, wstart
- i
))
237 wvalue
<<= (i
- wend
);
243 /* wend is the size of the current window */
245 /* add the 'bytes above' */
247 for(i
= 0; i
< j
; i
++)
249 if(!BN_mod_mul(r
, r
, r
, m
, ctx
))
253 /* wvalue will be an odd number < 2^window */
254 if(!BN_mod_mul(r
, r
, &(val
[wvalue
>> 1]), m
, ctx
))
257 /* move the 'window' down further */
261 if(wstart
< 0) { break; }
266 for(i
= 0; i
< ts
; i
++)
267 { BN_clear_free(&(val
[i
])); }
272 BN_nnmod(BIGNUM
*r
, const BIGNUM
*m
, const BIGNUM
*d
, BN_CTX
*ctx
)
274 /* like BN_mod, but returns non-negative remainder
275 * (i.e., 0 <= r < |d| always holds)
278 if (!(BN_mod(r
, m
, d
, ctx
)))
282 /* now -|d| < r < 0, so we have to set r : = r + |d| */
283 return (d
->neg
? BN_sub
: BN_add
)(r
, r
, d
);
286 /* solves ax == 1 (mod n) */
288 BN_mod_inverse(BIGNUM
*ret
, BIGNUM
*a
, const BIGNUM
*n
, BN_CTX
*ctx
)
290 BIGNUM
*A
, *B
, *X
, *Y
, *M
, *D
, *T
= NULL
;
304 if (T
== NULL
) goto err
;
306 if (ret
== NULL
) goto err
;
310 if (BN_copy(B
, a
) == NULL
) goto err
;
311 if (BN_copy(A
, n
) == NULL
) goto err
;
313 if (B
->neg
|| (BN_ucmp(B
, A
) >= 0)) {
314 if (!BN_nnmod(B
, B
, A
, ctx
)) goto err
;
317 /* From B = a mod |n|, A = |n| it follows that
320 * -sign*X*a == B (mod |n|),
321 * sign*Y*a == A (mod |n|).
324 if (BN_is_odd(n
) && (BN_num_bits(n
) <= (BN_BITS
<= 32 ? 450 : 2048))) {
325 /* Binary inversion algorithm; requires odd modulus.
326 * This is faster than the general algorithm if the modulus
327 * is sufficiently small (about 400 .. 500 bits on 32-bit
328 * sytems, but much more on 64-bit systems)
332 while (!BN_is_zero(B
)) {
336 * (1) -sign*X*a == B (mod |n|),
337 * (2) sign*Y*a == A (mod |n|)
340 /* Now divide B by the maximum possible power of two in the integers,
341 * and divide X by the same value mod |n|.
342 * When we're done, (1) still holds.
345 while (!BN_is_bit_set(B
, shift
)) /* note that 0 < B */ {
349 if (!BN_uadd(X
, X
, n
)) goto err
;
351 /* now X is even, so we can easily divide it by two */
352 if (!BN_rshift1(X
, X
)) goto err
;
355 if (!BN_rshift(B
, B
, shift
)) goto err
;
359 /* Same for A and Y. Afterwards, (2) still holds. */
361 while (!BN_is_bit_set(A
, shift
)) /* note that 0 < A */ {
365 if (!BN_uadd(Y
, Y
, n
)) goto err
;
368 if (!BN_rshift1(Y
, Y
)) goto err
;
371 if (!BN_rshift(A
, A
, shift
)) goto err
;
374 /* We still have (1) and (2).
375 * Both A and B are odd.
376 * The following computations ensure that
380 * (1) -sign*X*a == B (mod |n|),
381 * (2) sign*Y*a == A (mod |n|),
383 * and that either A or B is even in the next iteration.
385 if (BN_ucmp(B
, A
) >= 0) {
386 /* -sign*(X + Y)*a == B - A (mod |n|) */
387 if (!BN_uadd(X
, X
, Y
)) goto err
;
388 /* NB: we could use BN_mod_add_quick(X, X, Y, n), but that
389 * actually makes the algorithm slower
391 if (!BN_usub(B
, B
, A
)) goto err
;
393 /* sign*(X + Y)*a == A - B (mod |n|) */
394 if (!BN_uadd(Y
, Y
, X
)) goto err
;
395 /* as above, BN_mod_add_quick(Y, Y, X, n) would slow things down */
396 if (!BN_usub(A
, A
, B
)) goto err
;
400 /* general inversion algorithm */
402 while (!BN_is_zero(B
)) {
407 * (*) -sign*X*a == B (mod |n|),
408 * sign*Y*a == A (mod |n|)
411 /* (D, M) : = (A/B, A%B) ... */
412 if (BN_num_bits(A
) == BN_num_bits(B
)) {
413 if (!BN_one(D
)) goto err
;
414 if (!BN_sub(M
, A
, B
)) goto err
;
415 } else if (BN_num_bits(A
) == BN_num_bits(B
) + 1) {
416 /* A/B is 1, 2, or 3 */
417 if (!BN_lshift1(T
, B
)) goto err
;
418 if (BN_ucmp(A
, T
) < 0) {
419 /* A < 2*B, so D = 1 */
420 if (!BN_one(D
)) goto err
;
421 if (!BN_sub(M
, A
, B
)) goto err
;
423 /* A >= 2*B, so D = 2 or D = 3 */
424 if (!BN_sub(M
, A
, T
)) goto err
;
425 if (!BN_add(D
, T
, B
)) goto err
;
426 /* use D ( := 3 * B) as temp */
427 if (BN_ucmp(A
, D
) < 0) {
428 /* A < 3*B, so D = 2 */
429 if (!BN_set_word(D
, 2)) goto err
;
430 /* M ( = A - 2*B) already has the correct value */
432 /* only D = 3 remains */
433 if (!BN_set_word(D
, 3)) goto err
;
434 /* currently M = A - 2 * B,
435 * but we need M = A - 3 * B
437 if (!BN_sub(M
, M
, B
)) goto err
;
441 if (!BN_div(D
, M
, A
, B
, ctx
)) goto err
;
447 * (**) sign*Y*a == D*B + M (mod |n|).
450 tmp
= A
; /* keep the BIGNUM object, the value does not matter */
452 /* (A, B) : = (B, A mod B) ... */
455 /* ... so we have 0 <= B < A again */
457 /* Since the former M is now B and the former B is now A,
458 * (**) translates into
459 * sign*Y*a == D*A + B (mod |n|),
461 * sign*Y*a - D*A == B (mod |n|).
462 * Similarly, (*) translates into
463 * -sign*X*a == A (mod |n|).
466 * sign*Y*a + D*sign*X*a == B (mod |n|),
468 * sign*(Y + D*X)*a == B (mod |n|).
470 * So if we set (X, Y, sign) : = (Y + D*X, X, -sign), we arrive back at
471 * -sign*X*a == B (mod |n|),
472 * sign*Y*a == A (mod |n|).
473 * Note that X and Y stay non-negative all the time.
476 /* most of the time D is very small, so we can optimize tmp : = D*X+Y */
478 if (!BN_add(tmp
, X
, Y
)) goto err
;
480 if (BN_is_word(D
, 2)) {
481 if (!BN_lshift1(tmp
, X
)) goto err
;
482 } else if (BN_is_word(D
, 4)) {
483 if (!BN_lshift(tmp
, X
, 2)) goto err
;
484 } else if (D
->top
== 1) {
485 if (!BN_copy(tmp
, X
)) goto err
;
486 if (!BN_mul_word(tmp
, D
->d
[0])) goto err
;
488 if (!BN_mul(tmp
, D
, X
, ctx
)) goto err
;
490 if (!BN_add(tmp
, tmp
, Y
)) goto err
;
493 M
= Y
; /* keep the BIGNUM object, the value does not matter */
501 * The while loop (Euclid's algorithm) ends when
504 * sign*Y*a == A (mod |n|),
505 * where Y is non-negative.
509 if (!BN_sub(Y
, n
, Y
)) goto err
;
511 /* Now Y*a == A (mod |n|). */
515 /* Y*a == 1 (mod |n|) */
516 if (!Y
->neg
&& BN_ucmp(Y
, n
) < 0) {
517 if (!BN_copy(ret
, Y
)) goto err
;
519 if (!BN_nnmod(ret
, Y
, n
, ctx
)) goto err
;