1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-28 18:38:39 +00:00

bignum: Fix bn_digitcount

bn_digitcount used to use bn_bitcount. This would give the maximum
digits, which would often be higher than the actual number. This would
result in leading zeroes in bn_format.
This commit is contained in:
Saleem Rashid 2017-07-27 19:25:00 +01:00 committed by Pavol Rusnak
parent 43ea1392f2
commit 85cb0b4f2c
2 changed files with 26 additions and 10 deletions

View File

@ -195,6 +195,31 @@ int bn_bitcount(const bignum256 *a)
return 0;
}
#define DIGITS 78 // log10(2 ^ 256)
unsigned int bn_digitcount(const bignum256 *a)
{
bignum256 val;
memcpy(&val, a, sizeof(bignum256));
unsigned int digits = 1;
for (unsigned int i = 0; i < DIGITS; i += 3) {
uint32_t limb;
bn_divmod1000(&val, &limb);
if (limb >= 100) {
digits = i + 3;
} else if (limb >= 10) {
digits = i + 2;
} else if (limb >= 1) {
digits = i + 1;
}
}
return digits;
}
// sets a bignum to zero.
void bn_zero(bignum256 *a)
{

View File

@ -83,16 +83,7 @@ static inline void bn_copy(const bignum256 *a, bignum256 *b) {
int bn_bitcount(const bignum256 *a);
static inline int bn_digitcount(const bignum256 *a)
{
int bitcount = bn_bitcount(a);
if (bitcount == 256) {
return 78;
} else {
return bitcount * 78 / 256 + 1;
}
}
unsigned int bn_digitcount(const bignum256 *a);
void bn_zero(bignum256 *a);