Merge pull request #7564 from gabor-mezei-arm/7262_fix_ouput_width_in_ecc_mod_koblitz

[Bignum] Fix output width in ecp_mod_koblitz()
diff --git a/library/ecp_curves.c b/library/ecp_curves.c
index db35e96..b07753a 100644
--- a/library/ecp_curves.c
+++ b/library/ecp_curves.c
@@ -5533,7 +5533,6 @@
  * with R about 33 bits, used by the Koblitz curves.
  *
  * Write N as A0 + 2^224 A1, return A0 + R * A1.
- * Actually do two passes, since R is big.
  */
 #define P_KOBLITZ_R     (8 / sizeof(mbedtls_mpi_uint))            // Limbs in R
 
@@ -5571,7 +5570,11 @@
         mask  = ((mbedtls_mpi_uint) 1 << shift) - 1;
     }
 
-    for (size_t pass = 0; pass < 2; pass++) {
+    /* Two passes are needed to reduce the value of `A0 + R * A1` and then
+     * we need an additional one to reduce the possible overflow during
+     * the addition.
+     */
+    for (size_t pass = 0; pass < 3; pass++) {
         /* Copy A1 */
         memcpy(A1, X + P_limbs - adjust, P_limbs * ciL);
 
diff --git a/scripts/mbedtls_dev/ecp.py b/scripts/mbedtls_dev/ecp.py
index 2dae703..5f0efcf 100644
--- a/scripts/mbedtls_dev/ecp.py
+++ b/scripts/mbedtls_dev/ecp.py
@@ -518,6 +518,10 @@
         ("fffffffffffffffffffffffffffffffffffffffdffffdc6c"
          "0000000000000000000000000000000100002394013c7364"),
 
+        # Test case for overflow during addition
+        ("00000007ffff71b809e27dd832cfd5e04d9d2dbb9f8da217"
+         "0000000000000000000000000000000000000000520834f0"),
+
         # First 8 number generated by random.getrandbits(384) - seed(2,2)
         ("cf1822ffbc6887782b491044d5e341245c6e433715ba2bdd"
          "177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"),
@@ -582,6 +586,10 @@
         ("fffffffffffffffffffffffffffffffffffffffffffffffdffffcad8"
          "00000000000000000000000000000000000000010000352802c26590"),
 
+        # Test case for overflow during addition
+        ("0000007ffff2b68161180fd8cd92e1a109be158a19a99b1809db8032"
+         "0000000000000000000000000000000000000000000000000bf04f49"),
+
         # First 8 number generated by random.getrandbits(448) - seed(2,2)
         ("da94e3e8ab73738fcf1822ffbc6887782b491044d5e341245c6e4337"
          "15ba2bdd177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"),
@@ -647,6 +655,10 @@
         ("fffffffffffffffffffffffffffffffffffffffffffffffffffffffdfffff85c0"
          "00000000000000000000000000000000000000000000001000007a4000e9844"),
 
+        # Test case for overflow during addition
+        ("0000fffffc2f000e90a0c86a0a63234e5ba641f43a7e4aecc4040e67ec850562"
+         "00000000000000000000000000000000000000000000000000000000585674fd"),
+
         # First 8 number generated by random.getrandbits(512) - seed(2,2)
         ("4067c3584ee207f8da94e3e8ab73738fcf1822ffbc6887782b491044d5e34124"
          "5c6e433715ba2bdd177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"),