1
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
3
* LibTomCrypt is a library that provides various cryptographic
4
* algorithms in a highly modular and flexible manner.
6
* The library is free for all purposes without any express
9
* Tom St Denis, tomstdenis@iahu.ca, http://libtomcrypt.org
12
/* RSA Code by Tom St Denis */
17
/* compute an RSA modular exponentiation */
18
int rsa_exptmod(const unsigned char *in, unsigned long inlen,
19
unsigned char *out, unsigned long *outlen, int which,
20
prng_state *prng, int prng_idx,
23
mp_int tmp, tmpa, tmpb;
29
_ARGCHK(outlen != NULL);
33
if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
37
/* is the key of the right type for the operation? */
38
if (which == PK_PRIVATE && (key->type != PK_PRIVATE)) {
39
return CRYPT_PK_NOT_PRIVATE;
42
/* must be a private or public operation */
43
if (which != PK_PRIVATE && which != PK_PUBLIC) {
44
return CRYPT_PK_INVALID_TYPE;
47
/* init and copy into tmp */
48
if ((err = mp_init_multi(&tmp, &tmpa, &tmpb, NULL)) != MP_OKAY) { return mpi_to_ltc_error(err); }
49
if ((err = mp_read_unsigned_bin(&tmp, (unsigned char *)in, (int)inlen)) != MP_OKAY) { goto error; }
51
/* sanity check on the input */
52
if (mp_cmp(&key->N, &tmp) == MP_LT) {
53
err = CRYPT_PK_INVALID_SIZE;
57
/* are we using the private exponent and is the key optimized? */
58
if (which == PK_PRIVATE) {
59
/* tmpa = tmp^dP mod p */
60
if ((err = tim_exptmod(prng, prng_idx, &tmp, &key->e, &key->dP, &key->p, &tmpa)) != MP_OKAY) { goto error; }
62
/* tmpb = tmp^dQ mod q */
63
if ((err = tim_exptmod(prng, prng_idx, &tmp, &key->e, &key->dQ, &key->q, &tmpb)) != MP_OKAY) { goto error; }
65
/* tmp = (tmpa - tmpb) * qInv (mod p) */
66
if ((err = mp_sub(&tmpa, &tmpb, &tmp)) != MP_OKAY) { goto error; }
67
if ((err = mp_mulmod(&tmp, &key->qP, &key->p, &tmp)) != MP_OKAY) { goto error; }
69
/* tmp = tmpb + q * tmp */
70
if ((err = mp_mul(&tmp, &key->q, &tmp)) != MP_OKAY) { goto error; }
71
if ((err = mp_add(&tmp, &tmpb, &tmp)) != MP_OKAY) { goto error; }
74
if ((err = mp_exptmod(&tmp, &key->e, &key->N, &tmp)) != MP_OKAY) { goto error; }
78
x = (unsigned long)mp_unsigned_bin_size(&key->N);
80
err = CRYPT_BUFFER_OVERFLOW;
87
if ((err = mp_to_unsigned_bin(&tmp, out+(x-mp_unsigned_bin_size(&tmp)))) != MP_OKAY) { goto error; }
89
/* clean up and return */
93
err = mpi_to_ltc_error(err);
95
mp_clear_multi(&tmp, &tmpa, &tmpb, NULL);