Path: blob/master/libs/tomcrypt/src/stream/rc4/rc4_stream.c
5972 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/89#include "tomcrypt.h"1011#ifdef LTC_RC4_STREAM1213/**14Initialize an RC4 context (only the key)15@param st [out] The destination of the RC4 state16@param key The secret key17@param keylen The length of the secret key (8 - 256 bytes)18@return CRYPT_OK if successful19*/20int rc4_stream_setup(rc4_state *st, const unsigned char *key, unsigned long keylen)21{22unsigned char tmp, *s;23int x, y;24unsigned long j;2526LTC_ARGCHK(st != NULL);27LTC_ARGCHK(key != NULL);28LTC_ARGCHK(keylen >= 5); /* 40-2048 bits */2930s = st->buf;31for (x = 0; x < 256; x++) {32s[x] = x;33}3435for (j = x = y = 0; x < 256; x++) {36y = (y + s[x] + key[j++]) & 255;37if (j == keylen) {38j = 0;39}40tmp = s[x]; s[x] = s[y]; s[y] = tmp;41}42st->x = 0;43st->y = 0;4445return CRYPT_OK;46}4748/**49Encrypt (or decrypt) bytes of ciphertext (or plaintext) with RC450@param st The RC4 state51@param in The plaintext (or ciphertext)52@param inlen The length of the input (octets)53@param out [out] The ciphertext (or plaintext), length inlen54@return CRYPT_OK if successful55*/56int rc4_stream_crypt(rc4_state *st, const unsigned char *in, unsigned long inlen, unsigned char *out)57{58unsigned char x, y, *s, tmp;5960LTC_ARGCHK(st != NULL);61LTC_ARGCHK(in != NULL);62LTC_ARGCHK(out != NULL);6364x = st->x;65y = st->y;66s = st->buf;67while (inlen--) {68x = (x + 1) & 255;69y = (y + s[x]) & 255;70tmp = s[x]; s[x] = s[y]; s[y] = tmp;71tmp = (s[x] + s[y]) & 255;72*out++ = *in++ ^ s[tmp];73}74st->x = x;75st->y = y;76return CRYPT_OK;77}7879/**80Generate a stream of random bytes via RC481@param st The RC420 state82@param out [out] The output buffer83@param outlen The output length84@return CRYPT_OK on success85*/86int rc4_stream_keystream(rc4_state *st, unsigned char *out, unsigned long outlen)87{88if (outlen == 0) return CRYPT_OK; /* nothing to do */89LTC_ARGCHK(out != NULL);90XMEMSET(out, 0, outlen);91return rc4_stream_crypt(st, out, outlen, out);92}9394/**95Terminate and clear RC4 state96@param st The RC4 state97@return CRYPT_OK on success98*/99int rc4_stream_done(rc4_state *st)100{101LTC_ARGCHK(st != NULL);102XMEMSET(st, 0, sizeof(rc4_state));103return CRYPT_OK;104}105106#endif107108109