| // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #include <openssl/bn.h> |
| 16 |
| 17 | #include <openssl/err.h> |
| 18 |
| 19 | #include "internal.h" |
| 20 |
| 21 |
| 22 | // least significant word |
| 23 | #define BN_lsw(n) (((n)->width == 0) ? (BN_ULONG) 0 : (n)->d[0]) |
| 24 |
| 25 | int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { |
| 26 | // In 'tab', only odd-indexed entries are relevant: |
| 27 | // For any odd BIGNUM n, |
| 28 | // tab[BN_lsw(n) & 7] |
| 29 | // is $(-1)^{(n^2-1)/8}$ (using TeX notation). |
| 30 | // Note that the sign of n does not matter. |
| 31 | static const int tab[8] = {0, 1, 0, -1, 0, -1, 0, 1}; |
| 32 |
| 33 | // The Jacobi symbol is only defined for odd modulus. |
| 34 | if (!BN_is_odd(b)) { |
| 35 | OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS); |
| 36 | return -2; |
| 37 | } |
| 38 |
| 39 | // Require b be positive. |
| 40 | if (BN_is_negative(b)) { |
| 41 | OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); |
| 42 | return -2; |
| 43 | } |
| 44 |
| 45 | int ret = -2; |
| 46 | BN_CTX_start(ctx); |
| 47 | BIGNUM *A = BN_CTX_get(ctx); |
| 48 | BIGNUM *B = BN_CTX_get(ctx); |
| 49 | if (B == NULL) { |
| 50 | goto end; |
| 51 | } |
| 52 |
| 53 | if (!BN_copy(A, a) || |
| 54 | !BN_copy(B, b)) { |
| 55 | goto end; |
| 56 | } |
| 57 |
| 58 | // Adapted from logic to compute the Kronecker symbol, originally implemented |
| 59 | // according to Henri Cohen, "A Course in Computational Algebraic Number |
| 60 | // Theory" (algorithm 1.4.10). |
| 61 |
| 62 | ret = 1; |
| 63 |
| 64 | while (1) { |
| 65 | // Cohen's step 3: |
| 66 |
| 67 | // B is positive and odd |
| 68 | if (BN_is_zero(A)) { |
| 69 | ret = BN_is_one(B) ? ret : 0; |
| 70 | goto end; |
| 71 | } |
| 72 |
| 73 | // now A is non-zero |
| 74 | int i = 0; |
| 75 | while (!BN_is_bit_set(A, i)) { |
| 76 | i++; |
| 77 | } |
| 78 | if (!BN_rshift(A, A, i)) { |
| 79 | ret = -2; |
| 80 | goto end; |
| 81 | } |
| 82 | if (i & 1) { |
| 83 | // i is odd |
| 84 | // multiply 'ret' by $(-1)^{(B^2-1)/8}$ |
| 85 | ret = ret * tab[BN_lsw(B) & 7]; |
| 86 | } |
| 87 |
| 88 | // Cohen's step 4: |
| 89 | // multiply 'ret' by $(-1)^{(A-1)(B-1)/4}$ |
| 90 | if ((A->neg ? ~BN_lsw(A) : BN_lsw(A)) & BN_lsw(B) & 2) { |
| 91 | ret = -ret; |
| 92 | } |
| 93 |
| 94 | // (A, B) := (B mod |A|, |A|) |
| 95 | if (!BN_nnmod(B, B, A, ctx)) { |
| 96 | ret = -2; |
| 97 | goto end; |
| 98 | } |
| 99 | BIGNUM *tmp = A; |
| 100 | A = B; |
| 101 | B = tmp; |
| 102 | tmp->neg = 0; |
| 103 | } |
| 104 |
| 105 | end: |
| 106 | BN_CTX_end(ctx); |
| 107 | return ret; |
| 108 | } |
| 109 |