[PATCH] MPI helper of addition one limb, Least Leak Intended

Jussi Kivilinna jussi.kivilinna at iki.fi
Fri Feb 14 09:35:58 CET 2025


On 14.2.2025 3.25, NIIBE Yutaka via Gcrypt-devel wrote:
> Hello,
> 
> This change introduces a function _gcry_mpih_add_1_lli for one limb
> addition with least leak.
> 
> diff --git a/mpi/mpi-inline.h b/mpi/mpi-inline.h
> index 090e8a94..6954affb 100644
> --- a/mpi/mpi-inline.h
> +++ b/mpi/mpi-inline.h
> @@ -68,6 +68,28 @@ _gcry_mpih_add_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
>   }
>   
>   
> +/* Do same calculation as _gcry_mpih_add_1 does (under the condition
> +   of RES_PTR == S1_PTR), Least Leak Intended.  */
> +static inline mpi_limb_t
> +_gcry_mpih_add_1_lli (mpi_ptr_t s1_ptr, mpi_size_t s1_size, mpi_limb_t s2_limb)
> +{
> +  mpi_limb_t x;
> +  mpi_limb_t cy;
> +
> +  x = *s1_ptr;
> +  s2_limb += x;
> +  *s1_ptr++ = s2_limb;
> +  cy = (s2_limb < x);
> +  while ( --s1_size )
> +    {
> +      x = *s1_ptr + cy;
> +      *s1_ptr++ = x;
> +      cy = mpih_limb_is_zero (x) & mpih_limb_is_not_zero (cy);
> +    }
> +
> +  return cy;

I think this function could use 'add_ssaaaa' macro to handle addition with
carry.

Something like this (completely untested):

   cy = s2_limb;
   while ( s1_size )
     {
       x = *s1_ptr;
       add_ssaaaa(cy, x, 0, cy, 0, x);
       *s1_ptr++ = x;
       s1_size--;
     }
   return cy;

-Jussi



More information about the Gcrypt-devel mailing list