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
15 Initialize an RC4 context (only the key)
16 @param st [out] The destination of the RC4 state
17 @param key The secret key
18 @param keylen The length of the secret key (8 - 256 bytes)
19 @return CRYPT_OK if successful
21 int rc4_stream_setup(rc4_state *st, const unsigned char *key, unsigned long keylen)
23 unsigned char tmp, *s;
27 LTC_ARGCHK(st != NULL);
28 LTC_ARGCHK(key != NULL);
29 LTC_ARGCHK(keylen >= 5); /* 40-2048 bits */
32 for (x = 0; x < 256; x++) {
36 for (j = x = y = 0; x < 256; x++) {
37 y = (y + s[x] + key[j++]) & 255;
41 tmp = s[x]; s[x] = s[y]; s[y] = tmp;
50 Encrypt (or decrypt) bytes of ciphertext (or plaintext) with RC4
51 @param st The RC4 state
52 @param in The plaintext (or ciphertext)
53 @param inlen The length of the input (octets)
54 @param out [out] The ciphertext (or plaintext), length inlen
55 @return CRYPT_OK if successful
57 int rc4_stream_crypt(rc4_state *st, const unsigned char *in, unsigned long inlen, unsigned char *out)
59 unsigned char x, y, *s, tmp;
61 LTC_ARGCHK(st != NULL);
62 LTC_ARGCHK(in != NULL);
63 LTC_ARGCHK(out != NULL);
71 tmp = s[x]; s[x] = s[y]; s[y] = tmp;
72 tmp = (s[x] + s[y]) & 255;
73 *out++ = *in++ ^ s[tmp];
81 Generate a stream of random bytes via RC4
82 @param st The RC420 state
83 @param out [out] The output buffer
84 @param outlen The output length
85 @return CRYPT_OK on success
87 int rc4_stream_keystream(rc4_state *st, unsigned char *out, unsigned long outlen)
89 if (outlen == 0) return CRYPT_OK; /* nothing to do */
90 LTC_ARGCHK(out != NULL);
91 XMEMSET(out, 0, outlen);
92 return rc4_stream_crypt(st, out, outlen, out);
96 Terminate and clear RC4 state
97 @param st The RC4 state
98 @return CRYPT_OK on success
100 int rc4_stream_done(rc4_state *st)
102 LTC_ARGCHK(st != NULL);
103 XMEMSET(st, 0, sizeof(rc4_state));
109 /* ref: $Format:%D$ */
110 /* git commit: $Format:%H$ */
111 /* commit time: $Format:%ai$ */