| 1 |
// Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
#include <openssl/bn.h> |
| 5 |
|
| 6 |
#include <openssl/err.h> |
| 7 |
|
| 8 |
#include "internal.h" |
| 9 |
|
| 10 |
|
| 11 |
// least significant word |
| 12 |
#define BN_lsw(n) (((n)->width == 0) ? (BN_ULONG) 0 : (n)->d[0]) |
| 13 |
|
| 14 |
int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { |
| 15 |
// In 'tab', only odd-indexed entries are relevant: |
| 16 |
// For any odd BIGNUM n, |
| 17 |
// tab[BN_lsw(n) & 7] |
| 18 |
// is $(-1)^{(n^2-1)/8}$ (using TeX notation). |
| 19 |
// Note that the sign of n does not matter. |
| 20 |
static const int tab[8] = {0, 1, 0, -1, 0, -1, 0, 1}; |
| 21 |
|
| 22 |
// The Jacobi symbol is only defined for odd modulus. |
| 23 |
if (!BN_is_odd(b)) { |
| 24 |
OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS); |
| 25 |
return -2; |
| 26 |
} |
| 27 |
|
| 28 |
// Require b be positive. |
| 29 |
if (BN_is_negative(b)) { |
| 30 |
OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); |
| 31 |
return -2; |
| 32 |
} |
| 33 |
|
| 34 |
int ret = -2; |
| 35 |
BN_CTX_start(ctx); |
| 36 |
BIGNUM *A = BN_CTX_get(ctx); |
| 37 |
BIGNUM *B = BN_CTX_get(ctx); |
| 38 |
if (B == NULL) { |
| 39 |
goto end; |
| 40 |
} |
| 41 |
|
| 42 |
if (!BN_copy(A, a) || |
| 43 |
!BN_copy(B, b)) { |
| 44 |
goto end; |
| 45 |
} |
| 46 |
|
| 47 |
// Adapted from logic to compute the Kronecker symbol, originally implemented |
| 48 |
// according to Henri Cohen, "A Course in Computational Algebraic Number |
| 49 |
// Theory" (algorithm 1.4.10). |
| 50 |
|
| 51 |
ret = 1; |
| 52 |
|
| 53 |
while (1) { |
| 54 |
// Cohen's step 3: |
| 55 |
|
| 56 |
// B is positive and odd |
| 57 |
if (BN_is_zero(A)) { |
| 58 |
ret = BN_is_one(B) ? ret : 0; |
| 59 |
goto end; |
| 60 |
} |
| 61 |
|
| 62 |
// now A is non-zero |
| 63 |
int i = 0; |
| 64 |
while (!BN_is_bit_set(A, i)) { |
| 65 |
i++; |
| 66 |
} |
| 67 |
if (!BN_rshift(A, A, i)) { |
| 68 |
ret = -2; |
| 69 |
goto end; |
| 70 |
} |
| 71 |
if (i & 1) { |
| 72 |
// i is odd |
| 73 |
// multiply 'ret' by $(-1)^{(B^2-1)/8}$ |
| 74 |
ret = ret * tab[BN_lsw(B) & 7]; |
| 75 |
} |
| 76 |
|
| 77 |
// Cohen's step 4: |
| 78 |
// multiply 'ret' by $(-1)^{(A-1)(B-1)/4}$ |
| 79 |
if ((A->neg ? ~BN_lsw(A) : BN_lsw(A)) & BN_lsw(B) & 2) { |
| 80 |
ret = -ret; |
| 81 |
} |
| 82 |
|
| 83 |
// (A, B) := (B mod |A|, |A|) |
| 84 |
if (!BN_nnmod(B, B, A, ctx)) { |
| 85 |
ret = -2; |
| 86 |
goto end; |
| 87 |
} |
| 88 |
BIGNUM *tmp = A; |
| 89 |
A = B; |
| 90 |
B = tmp; |
| 91 |
tmp->neg = 0; |
| 92 |
} |
| 93 |
|
| 94 |
end: |
| 95 |
BN_CTX_end(ctx); |
| 96 |
return ret; |
| 97 |
} |