Skip to content

Commit

Permalink
Fix some more negative zeros and add tests for each case.
Browse files Browse the repository at this point in the history
See openssl/openssl#1672.

Change-Id: I4c93a568b9b7ce582b03e955d3aa9cb6b0e89794
Reviewed-on: https://boringssl-review.googlesource.com/12314
Commit-Queue: David Benjamin <davidben@google.com>
Reviewed-by: Adam Langley <agl@google.com>
  • Loading branch information
davidben authored and agl committed Nov 16, 2016
1 parent ca0b603 commit 4008c7a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
31 changes: 31 additions & 0 deletions crypto/bn/bn_test.cc
Expand Up @@ -1203,6 +1203,37 @@ static bool TestNegativeZero(BN_CTX *ctx) {
return false;
}

// Test that |BN_rshift| and |BN_rshift1| will not produce a negative zero.
if (!BN_set_word(a.get(), 1)) {
return false;
}

BN_set_negative(a.get(), 1);
if (!BN_rshift(b.get(), a.get(), 1) ||
!BN_rshift1(c.get(), a.get())) {
return false;
}

if (!BN_is_zero(b.get()) || BN_is_negative(b.get())) {
fprintf(stderr, "BN_rshift(-1, 1) produced the wrong result.\n");
return false;
}

if (!BN_is_zero(c.get()) || BN_is_negative(c.get())) {
fprintf(stderr, "BN_rshift1(-1) produced the wrong result.\n");
return false;
}

// Test that |BN_div_word| will not produce a negative zero.
if (BN_div_word(a.get(), 2) == (BN_ULONG)-1) {
return false;
}

if (!BN_is_zero(a.get()) || BN_is_negative(a.get())) {
fprintf(stderr, "BN_div_word(-1, 2) produced the wrong result.\n");
return false;
}

return true;
}

Expand Down
4 changes: 4 additions & 0 deletions crypto/bn/div.c
Expand Up @@ -628,6 +628,10 @@ BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) {
a->top--;
}

if (a->top == 0) {
a->neg = 0;
}

ret >>= j;
return ret;
}
Expand Down
8 changes: 8 additions & 0 deletions crypto/bn/shift.c
Expand Up @@ -182,6 +182,10 @@ int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) {
}
}

if (r->top == 0) {
r->neg = 0;
}

return 1;
}

Expand Down Expand Up @@ -215,6 +219,10 @@ int BN_rshift1(BIGNUM *r, const BIGNUM *a) {
}
r->top = j;

if (r->top == 0) {
r->neg = 0;
}

return 1;
}

Expand Down

0 comments on commit 4008c7a

Please sign in to comment.