libtom / libtommath

LibTomMath is a free open source portable number theoretic multiple-precision integer library written entirely in C.
https://www.libtom.net
Other
645 stars 194 forks source link

Need help with mp_exptmod and BigInts #109

Closed waigel closed 6 years ago

waigel commented 6 years ago

I would like to calculate the following in C ++ with libtommath: x ^ (2 ^ level) % n

So I try it ...

        char buff[4096];
        mp_int x, level, n, X, e;

        mp_init(&x);
        mp_init(&level);
        mp_init(&n);
        mp_init(&X);
        mp_init(&e);

        // Calculate RSA  x ^ (2 ^ level) % n

        mp_set(&x, 32878006774570359216307190512414453734815024711845858985814302013359906676224571864057517441898232179839316906470039235887748992902358250854400787652810336070530280967470770997285440429053186803879037);
        mp_set(&level, 10000);
        mp_set(&n, 77898130960070341501772069500669364440519531421534783575397763758775619778096560479521554583192022357575799725548012588149166448319424189949242058358050730052508358466295626425829884371399991831978634);
        mp_set(&e, 2);

        mp_sqr(&e, &level);
        mp_toint(&level, buff);
        printf("LVL = %s\n", buff );  // 4
        mp_exptmod(&x, &level, &n, &X);

        mp_toint(&X, buff);
        printf("X :: %s\n", buff); // 346751013179386221

//Warning: integer constant is too large for its type mp_set(&n, ...);
//Warning: integer constant is too large for its type mp_set(&x, ...);

It just doesn't calculate the big numbers correct ... or I'm doing something wrong ...

czurnieden commented 6 years ago

Yes, you are doing something wrong, almost all, actually. mp_set accepts small integers only, not big integers, you need to read them in as strings with mp_read_radix(). To compute 2^level you need to use either mp_exp_d() or, much better here, just a shift with mp_mul_2d(). The function mp_sqr(a,b) does b = a^2 which is not what you want to do. The function mp_toint() is not able to do what you want, you need to use e.g. mp_toradix ().

LibTomMath has a lot of good documentation, please read it.

tomstdenis commented 6 years ago

I constantly in awe and impressed that this long after I (sadly) gave up working on the projects people still are working on them and improving them. :-) Thanks to all who support free open source software.

(quick note, In case people are wondering I actually do open source at AMD on the graphics side. So I'm still fighting the good fight, just have a family to feed now :-)).