Skip to content

Commit

Permalink
Avoid writing directly into fp_digits through char*.
Browse files Browse the repository at this point in the history
There are potential issues with weird platforms were not
all bits of a fp_digit are used (padding bits), plus it
makes it harder to do reproducible testing of algorithms.
  • Loading branch information
rasky authored and levitte committed Sep 18, 2024
1 parent df4f30a commit a1ad906
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/numtheory/fp_prime_random_ex.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
int fp_prime_random_ex(fp_int *a, int t, int size, int flags, tfm_prime_callback cb, void *dat)
{
fp_digit maskAND_msb, maskOR_lsb;
int res, dsize;
int res, bsize, dsize;
unsigned char buf[FP_SIZE * sizeof(fp_digit)];

/* sanity check the input */
if (size <= 1 || cb == NULL || t <= 0 || t > FP_PRIME_SIZE) {
Expand All @@ -26,6 +27,8 @@ int fp_prime_random_ex(fp_int *a, int t, int size, int flags, tfm_prime_callback

/* calc the size in fp_digit */
dsize = (size + DIGIT_BIT - 1) >> DIGIT_SHIFT;
/* calc the size in bytes */
bsize = (size + 7) >> 3;

/* calc the maskAND value for the MSbyte */
maskAND_msb = FP_MASK >> ((DIGIT_BIT - size) & (DIGIT_BIT-1));
Expand All @@ -38,14 +41,18 @@ int fp_prime_random_ex(fp_int *a, int t, int size, int flags, tfm_prime_callback

do {
/* read the bytes */
if (cb((unsigned char*)&a->dp[0], dsize*DIGIT_BIT, dat) != dsize*DIGIT_BIT) {
if (cb(buf, bsize, dat) != bsize) {
return FP_VAL;
}
a->used = dsize;
fp_read_unsigned_bin(a, buf, bsize);

/* make sure the MSbyte has the required number of bits */
a->dp[dsize-1] &= maskAND_msb;

/* Force a->used as well, it could be smaller if the highest bits were
generated as 0 by the callback. */
a->used = dsize;

/* modify the LSbyte as requested */
a->dp[0] |= maskOR_lsb;

Expand Down

0 comments on commit a1ad906

Please sign in to comment.