Probably bug with BigInt

Hi folks !

I have an issue with num_bigint::BigInt. I use it for SRP crypto-algorithm implementation and sometimes generated value is 1 byte less than expected. I noticed this depends on specific value of private_ephemeral which always equals to random 19 bytes. Initial data:

// below is pseudo-code

// always same
let generator: BigInt = 7;
// always same
let modulus: BigInt = 62100066509156017342069496140902949863249758336000796928566441170293728648119;

I generate private_ephemeral like this:

let private_ephemeral: [u8; 19] = rand::random();

and next I calculating public_ephemeral:

let public_ephemeral = generator.modpow(&private_ephemeral, &modulus);

public_ephemeral expected to be always 32 bytes length. But sometimes it is 31 bytes length.

This is small sandbox to reproduce, including correct and wrong values.

Could somebody explain me what could be wrong ?

A BigInt doesn't have an intrinsic byte-length based on the size of the input. It stores all the nonzero bits of the value.

So, if you have a uniformly distributed pseudorandom number of 32*8 bits, the highest 8 bits will be zero with probability 1/256, and in that case the vector will be 31 bytes or less.

4 Likes

Got it. Thank you for the explanation !

Since you know the expected size of your numbers you could also consider using a fixed-sized bigint implementation like the one in the bnum crate

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.