Skip to content

Incorrect value returned from cx_bn_cnt_bits #487

@aido

Description

@aido

The following function seems to return the bit position of the most significant bit in a big number:

speculos/src/bolos/cx_mpi.c

Lines 599 to 637 in 56ed996

uint32_t cx_mpi_cnt_bits(const cx_mpi_t *x)
{
uint8_t a[MAX_MPI_BYTE_SIZE];
uint32_t len, nbits;
uint8_t b;
uint8_t *p;
nbits = 0;
// Convert the bignum into big-endian form and store it in 'a':
// (no need to expand mod 16 and fill with 0, just go as fast as possible)
len = BN_num_bytes(x);
if (len > MAX_MPI_BYTE_SIZE) {
return CX_INVALID_PARAMETER;
}
// Convert a cx_mpi_t into big-endian bytes form:
len = BN_bn2bin(x, a);
p = a;
while (*p == 0) {
p++;
len--;
if (len == 0)
break;
}
if (len != 0) {
len = len * 8;
b = *p;
while ((b & 0x80) == 0) {
b = b << 1;
len--;
}
}
nbits = len;
return nbits;
}

Whereas the documentation suggests that it should instead return the number of bits set to 1 in a big number:

https://github.com/LedgerHQ/ledger-secure-sdk/blob/b82be6fd5a082132ee08bf0d105d1bb7bb4d0b41/include/ox_bn.h#L490-L502

Is the function incorrect or the documentation?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions