comparison rsa_exptmod.c @ 0:d7da3b1e1540 libtomcrypt

put back the 0.95 makefile which was inadvertently merged over
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:21:40 +0000
parents
children 6362d3854bb4
comparison
equal deleted inserted replaced
-1:000000000000 0:d7da3b1e1540
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 *
9 * Tom St Denis, [email protected], http://libtomcrypt.org
10 */
11
12 /* RSA Code by Tom St Denis */
13 #include "mycrypt.h"
14
15 #ifdef MRSA
16
17 int rsa_exptmod(const unsigned char *in, unsigned long inlen,
18 unsigned char *out, unsigned long *outlen, int which,
19 rsa_key *key)
20 {
21 mp_int tmp, tmpa, tmpb;
22 unsigned long x;
23 int err;
24
25 _ARGCHK(in != NULL);
26 _ARGCHK(out != NULL);
27 _ARGCHK(outlen != NULL);
28 _ARGCHK(key != NULL);
29
30 if (which == PK_PRIVATE && (key->type != PK_PRIVATE && key->type != PK_PRIVATE_OPTIMIZED)) {
31 return CRYPT_PK_NOT_PRIVATE;
32 }
33
34 /* must be a private or public operation */
35 if (which != PK_PRIVATE && which != PK_PUBLIC) {
36 return CRYPT_PK_INVALID_TYPE;
37 }
38
39 /* init and copy into tmp */
40 if ((err = mp_init_multi(&tmp, &tmpa, &tmpb, NULL)) != MP_OKAY) { goto error; }
41 if ((err = mp_read_unsigned_bin(&tmp, (unsigned char *)in, (int)inlen)) != MP_OKAY) { goto error; }
42
43 /* sanity check on the input */
44 if (mp_cmp(&key->N, &tmp) == MP_LT) {
45 err = CRYPT_PK_INVALID_SIZE;
46 goto done;
47 }
48
49 /* are we using the private exponent and is the key optimized? */
50 if (which == PK_PRIVATE && key->type == PK_PRIVATE_OPTIMIZED) {
51 /* tmpa = tmp^dP mod p */
52 if ((err = mp_exptmod(&tmp, &key->dP, &key->p, &tmpa)) != MP_OKAY) { goto error; }
53
54 /* tmpb = tmp^dQ mod q */
55 if ((err = mp_exptmod(&tmp, &key->dQ, &key->q, &tmpb)) != MP_OKAY) { goto error; }
56
57 /* tmp = tmpa*qP + tmpb*pQ mod N */
58 if ((err = mp_mul(&tmpa, &key->qP, &tmpa)) != MP_OKAY) { goto error; }
59 if ((err = mp_mul(&tmpb, &key->pQ, &tmpb)) != MP_OKAY) { goto error; }
60 if ((err = mp_addmod(&tmpa, &tmpb, &key->N, &tmp)) != MP_OKAY) { goto error; }
61 } else {
62 /* exptmod it */
63 if ((err = mp_exptmod(&tmp, which==PK_PRIVATE?&key->d:&key->e, &key->N, &tmp)) != MP_OKAY) { goto error; }
64 }
65
66 /* read it back */
67 x = (unsigned long)mp_unsigned_bin_size(&tmp);
68 if (x > *outlen) {
69 err = CRYPT_BUFFER_OVERFLOW;
70 goto done;
71 }
72 *outlen = x;
73
74 /* convert it */
75 if ((err = mp_to_unsigned_bin(&tmp, out)) != MP_OKAY) { goto error; }
76
77 /* clean up and return */
78 err = CRYPT_OK;
79 goto done;
80 error:
81 err = mpi_to_ltc_error(err);
82 done:
83 mp_clear_multi(&tmp, &tmpa, &tmpb, NULL);
84 return err;
85 }
86
87 #endif