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