view tim_exptmod.c @ 147:c2b93763dac9 libtomcrypt

Fixes for it to compile and work nicely with Dropbear. In particular, OS X's 'ar' doesn't seem to like arrays which don't have initialising values.
author Matt Johnston <matt@ucc.asn.au>
date Sun, 19 Dec 2004 16:23:32 +0000
parents 5d99163f7e32
children
line wrap: on
line source

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, [email protected], http://libtomcrypt.org
 */

/* RSA Code by Tom St Denis */
#include "mycrypt.h"

#ifdef RSA_TIMING

/* decrypts c into m */
int tim_exptmod(prng_state *prng, int prng_idx, 
                mp_int *c, mp_int *e, mp_int *d, mp_int *n, mp_int *m)
{
   int           err;
   mp_int        r, tmp, tmp2;
   unsigned char *rtmp;
   unsigned long rlen;

   _ARGCHK(c != NULL);
   _ARGCHK(e != NULL);
   _ARGCHK(d != NULL);
   _ARGCHK(n != NULL);
   _ARGCHK(m != NULL);

   if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
      return err;
   }

   /* pick random r */ 
   rlen = mp_unsigned_bin_size(n);
   rtmp = XMALLOC(rlen);
   if (rtmp == NULL) {
      return CRYPT_MEM;
   }

   /* read in random value "r" */
   if (prng_descriptor[prng_idx].read(rtmp, rlen, prng) != rlen) {
      XFREE(rtmp);
      return CRYPT_ERROR_READPRNG;
   }

   if ((err = mp_init_multi(&r, &tmp, &tmp2, NULL)) != MP_OKAY) {
      XFREE(rtmp);
      return mpi_to_ltc_error(err);
   }

   /* read in r */
   if ((err = mp_read_unsigned_bin(&r, rtmp, rlen)) != MP_OKAY)              { goto __ERR; }

   /* compute tmp = r^e */
   if ((err = mp_exptmod(&r, e, n, &tmp)) != MP_OKAY)                        { goto __ERR; }

   /* multiply C into the mix */
   if ((err = mp_mulmod(c, &tmp, n, &tmp)) != MP_OKAY)                       { goto __ERR; }

   /* raise to d */
   if ((err = mp_exptmod(&tmp, d, n, &tmp)) != MP_OKAY)                      { goto __ERR; }
   
   /* invert r and multiply */
   if ((err = mp_invmod(&r, n, &tmp2)) != MP_OKAY)                           { goto __ERR; }

   /* multiply and we are totally set */
   if ((err = mp_mulmod(&tmp, &tmp2, n, m)) != MP_OKAY)                      { goto __ERR; }

__ERR:  mp_clear_multi(&r, &tmp, &tmp2, NULL);
   XFREE(rtmp);
   return mpi_to_ltc_error(err);
}

#endif