blob: 15436230678d8d4731f941dadd844ef738d47a50 [file] [log] [blame]
Werner Lewis0c6ea122022-09-30 13:02:16 +01001/* BEGIN_HEADER */
2#include "mbedtls/bignum.h"
3#include "mbedtls/entropy.h"
4#include "bignum_mod.h"
5#include "constant_time_internal.h"
6#include "test/constant_flow.h"
7
8/* Check the validity of the sign bit in an MPI object. Reject representations
9 * that are not supported by the rest of the library and indicate a bug when
10 * constructing the value. */
11static int sign_is_valid( const mbedtls_mpi *X )
12{
13 if( X->s != 1 && X->s != -1 )
14 return( 0 ); // invalid sign bit, e.g. 0
15 if( mbedtls_mpi_bitlen( X ) == 0 && X->s != 1 )
16 return( 0 ); // negative zero
17 return( 1 );
18}
19
20/* END_HEADER */
21
22/* BEGIN_DEPENDENCIES
23 * depends_on:MBEDTLS_BIGNUM_C
24 * END_DEPENDENCIES
25 */
26
27/* BEGIN_CASE */
28void mpi_mod_setup( int ext_rep, int int_rep, int iret )
29{
30 #define MLIMBS 8
31 mbedtls_mpi_uint mp[MLIMBS];
32 mbedtls_mpi_mod_modulus m;
33 int ret;
34
35 memset( mp, 0xFF, sizeof(mp) );
36
37 mbedtls_mpi_mod_modulus_init( &m );
38 ret = mbedtls_mpi_mod_modulus_setup( &m, mp, MLIMBS, ext_rep, int_rep );
39 TEST_EQUAL( ret, iret );
40
41 /* Address sanitiser should catch if we try to free mp */
42 mbedtls_mpi_mod_modulus_free( &m );
43
44 /* Make sure that the modulus doesn't have reference to mp anymore */
45 TEST_ASSERT( m.p != mp );
46
47exit:
48 /* It should be safe to call an mbedtls free several times */
49 mbedtls_mpi_mod_modulus_free( &m );
50
51 #undef MLIMBS
52}
53/* END_CASE */
54
55
56/* BEGIN_CASE */
57void mpi_mod_mpi( char * input_X, char * input_Y,
58 char * input_A, int div_result )
59{
60 mbedtls_mpi X, Y, A;
61 int res;
62 mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &A );
63
64 TEST_ASSERT( mbedtls_test_read_mpi( &X, input_X ) == 0 );
65 TEST_ASSERT( mbedtls_test_read_mpi( &Y, input_Y ) == 0 );
66 TEST_ASSERT( mbedtls_test_read_mpi( &A, input_A ) == 0 );
67 res = mbedtls_mpi_mod_mpi( &X, &X, &Y );
68 TEST_ASSERT( res == div_result );
69 if( res == 0 )
70 {
71 TEST_ASSERT( sign_is_valid( &X ) );
72 TEST_ASSERT( mbedtls_mpi_cmp_mpi( &X, &A ) == 0 );
73 }
74
75exit:
76 mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &A );
77}
78/* END_CASE */
79
80/* BEGIN_CASE */
81void mpi_mod_int( char * input_X, int input_Y,
82 int input_A, int div_result )
83{
84 mbedtls_mpi X;
85 int res;
86 mbedtls_mpi_uint r;
87 mbedtls_mpi_init( &X );
88
89 TEST_ASSERT( mbedtls_test_read_mpi( &X, input_X ) == 0 );
90 res = mbedtls_mpi_mod_int( &r, &X, input_Y );
91 TEST_ASSERT( res == div_result );
92 if( res == 0 )
93 {
94 TEST_ASSERT( r == (mbedtls_mpi_uint) input_A );
95 }
96
97exit:
98 mbedtls_mpi_free( &X );
99}
100/* END_CASE */