comparison rc4.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 5d99163f7e32
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 #include "mycrypt.h"
12
13 #ifdef RC4
14
15 const struct _prng_descriptor rc4_desc =
16 {
17 "rc4",
18 &rc4_start,
19 &rc4_add_entropy,
20 &rc4_ready,
21 &rc4_read
22 };
23
24 int rc4_start(prng_state *prng)
25 {
26 _ARGCHK(prng != NULL);
27
28 /* set keysize to zero */
29 prng->rc4.x = 0;
30
31 return CRYPT_OK;
32 }
33
34 int rc4_add_entropy(const unsigned char *buf, unsigned long len, prng_state *prng)
35 {
36 _ARGCHK(buf != NULL);
37 _ARGCHK(prng != NULL);
38
39 if (prng->rc4.x + len > 256) {
40 return CRYPT_INVALID_KEYSIZE;
41 }
42
43 while (len--) {
44 prng->rc4.buf[prng->rc4.x++] = *buf++;
45 }
46
47 return CRYPT_OK;
48
49 }
50
51 int rc4_ready(prng_state *prng)
52 {
53 unsigned char key[256], tmp;
54 int keylen, x, y;
55
56 _ARGCHK(prng != NULL);
57
58 /* extract the key */
59 memcpy(key, prng->rc4.buf, 256);
60 keylen = prng->rc4.x;
61
62 /* make RC4 perm and shuffle */
63 for (x = 0; x < 256; x++) {
64 prng->rc4.buf[x] = x;
65 }
66
67 for (x = y = 0; x < 256; x++) {
68 y = (y + prng->rc4.buf[x] + key[x % keylen]) & 255;
69 tmp = prng->rc4.buf[x]; prng->rc4.buf[x] = prng->rc4.buf[y]; prng->rc4.buf[y] = tmp;
70 }
71 prng->rc4.x = x;
72 prng->rc4.y = y;
73
74 #ifdef CLEAN_STACK
75 zeromem(key, sizeof(key));
76 #endif
77
78 return CRYPT_OK;
79 }
80
81 unsigned long rc4_read(unsigned char *buf, unsigned long len, prng_state *prng)
82 {
83 int x, y;
84 unsigned char *s, tmp;
85 unsigned long n;
86
87 _ARGCHK(buf != NULL);
88 _ARGCHK(prng != NULL);
89
90 n = len;
91 x = prng->rc4.x;
92 y = prng->rc4.y;
93 s = prng->rc4.buf;
94 while (len--) {
95 x = (x + 1) & 255;
96 y = (y + s[x]) & 255;
97 tmp = s[x]; s[x] = s[y]; s[y] = tmp;
98 tmp = (s[x] + s[y]) & 255;
99 *buf++ ^= s[tmp];
100 }
101 prng->rc4.x = x;
102 prng->rc4.y = y;
103 return n;
104 }
105
106 #endif
107