15
|
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 RSA_TIMING |
|
16 |
|
17 /* decrypts c into m */ |
|
18 int tim_exptmod(prng_state *prng, int prng_idx, |
|
19 mp_int *c, mp_int *e, mp_int *d, mp_int *n, mp_int *m) |
|
20 { |
|
21 int err; |
|
22 mp_int r, tmp, tmp2; |
|
23 unsigned char *rtmp; |
|
24 unsigned long rlen; |
|
25 |
|
26 _ARGCHK(c != NULL); |
|
27 _ARGCHK(e != NULL); |
|
28 _ARGCHK(d != NULL); |
|
29 _ARGCHK(n != NULL); |
|
30 _ARGCHK(m != NULL); |
|
31 |
|
32 if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) { |
|
33 return err; |
|
34 } |
|
35 |
|
36 /* pick random r */ |
143
|
37 rlen = mp_unsigned_bin_size(n); |
|
38 rtmp = XMALLOC(rlen); |
15
|
39 if (rtmp == NULL) { |
|
40 return CRYPT_MEM; |
|
41 } |
|
42 |
143
|
43 /* read in random value "r" */ |
15
|
44 if (prng_descriptor[prng_idx].read(rtmp, rlen, prng) != rlen) { |
|
45 XFREE(rtmp); |
|
46 return CRYPT_ERROR_READPRNG; |
|
47 } |
|
48 |
|
49 if ((err = mp_init_multi(&r, &tmp, &tmp2, NULL)) != MP_OKAY) { |
|
50 XFREE(rtmp); |
|
51 return mpi_to_ltc_error(err); |
|
52 } |
|
53 |
|
54 /* read in r */ |
|
55 if ((err = mp_read_unsigned_bin(&r, rtmp, rlen)) != MP_OKAY) { goto __ERR; } |
|
56 |
|
57 /* compute tmp = r^e */ |
|
58 if ((err = mp_exptmod(&r, e, n, &tmp)) != MP_OKAY) { goto __ERR; } |
|
59 |
|
60 /* multiply C into the mix */ |
|
61 if ((err = mp_mulmod(c, &tmp, n, &tmp)) != MP_OKAY) { goto __ERR; } |
|
62 |
|
63 /* raise to d */ |
|
64 if ((err = mp_exptmod(&tmp, d, n, &tmp)) != MP_OKAY) { goto __ERR; } |
|
65 |
|
66 /* invert r and multiply */ |
|
67 if ((err = mp_invmod(&r, n, &tmp2)) != MP_OKAY) { goto __ERR; } |
|
68 |
|
69 /* multiply and we are totally set */ |
|
70 if ((err = mp_mulmod(&tmp, &tmp2, n, m)) != MP_OKAY) { goto __ERR; } |
|
71 |
|
72 __ERR: mp_clear_multi(&r, &tmp, &tmp2, NULL); |
|
73 XFREE(rtmp); |
|
74 return mpi_to_ltc_error(err); |
|
75 } |
|
76 |
|
77 #endif |