bignum_common.py: Added `bits_to_limbs` method.
This patch introduces a rounding-error-resiliant method to
calculate bits_to_limbs, and is updating `SECP224R1` and
`SECP224K1` to use it.
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
diff --git a/scripts/mbedtls_dev/bignum_common.py b/scripts/mbedtls_dev/bignum_common.py
index 51b25a3..3bef16d 100644
--- a/scripts/mbedtls_dev/bignum_common.py
+++ b/scripts/mbedtls_dev/bignum_common.py
@@ -19,6 +19,7 @@
from typing import Iterator, List, Tuple, TypeVar, Any
from copy import deepcopy
from itertools import chain
+from math import ceil
from . import test_case
from . import test_data_generation
@@ -76,9 +77,14 @@
"""Return all pair combinations from input values."""
return [(x, y) for x in values for y in values]
+def bits_to_limbs(bits: int, bits_in_limb: int) -> int:
+ """ Return the appropriate ammount of limbs needed to store
+ a number contained in input bits"""
+ return ceil(bits / bits_in_limb)
+
def hex_digits_for_limb(limbs: int, bits_in_limb: int) -> int:
- """ Retrun the hex digits need for a number of limbs. """
- return 2 * (limbs * bits_in_limb // 8)
+ """ Return the hex digits need for a number of limbs. """
+ return 2 * ((limbs * bits_in_limb) // 8)
def hex_digits_max_int(val: str, bits_in_limb: int) -> int:
""" Return the first number exceeding maximum the limb space
diff --git a/scripts/mbedtls_dev/ecp.py b/scripts/mbedtls_dev/ecp.py
index 8a3ab28..ed79a07 100644
--- a/scripts/mbedtls_dev/ecp.py
+++ b/scripts/mbedtls_dev/ecp.py
@@ -165,7 +165,8 @@
@property
def arg_a(self) -> str:
- hex_digits = bignum_common.hex_digits_for_limb(448 // self.bits_in_limb, self.bits_in_limb)
+ limbs = 2 * bignum_common.bits_to_limbs(224, self.bits_in_limb)
+ hex_digits = bignum_common.hex_digits_for_limb(limbs, self.bits_in_limb)
return super().format_arg('{:x}'.format(self.int_a)).zfill(hex_digits)
def result(self) -> List[str]:
@@ -624,7 +625,8 @@
@property
def arg_a(self) -> str:
- hex_digits = bignum_common.hex_digits_for_limb(448 // self.bits_in_limb, self.bits_in_limb)
+ limbs = 2 * bignum_common.bits_to_limbs(224, self.bits_in_limb)
+ hex_digits = bignum_common.hex_digits_for_limb(limbs, self.bits_in_limb)
return super().format_arg('{:x}'.format(self.int_a)).zfill(hex_digits)
def result(self) -> List[str]: