Make arc4 more streamy

This commit is contained in:
Neale Pickett 2010-09-21 21:59:49 -06:00
parent e730b0766d
commit edf695a35e
2 changed files with 18 additions and 16 deletions

View File

@ -4,6 +4,12 @@
#define swap(a, b) do {int _swap=a; a=b, b=_swap;} while (0) #define swap(a, b) do {int _swap=a; a=b, b=_swap;} while (0)
struct arc4_ctx {
uint8_t S[256];
uint8_t i;
uint8_t j;
};
void void
arc4_init(struct arc4_ctx *ctx, uint8_t const *key, size_t keylen) arc4_init(struct arc4_ctx *ctx, uint8_t const *key, size_t keylen)
{ {
@ -22,25 +28,24 @@ arc4_init(struct arc4_ctx *ctx, uint8_t const *key, size_t keylen)
ctx->j = 0; ctx->j = 0;
} }
uint8_t
arc4_pad(struct arc4_ctx *ctx)
{
ctx->i = (ctx->i + 1) % 256;
ctx->j = (ctx->j + ctx->S[ctx->i]) % 256;
swap(ctx->S[ctx->i], ctx->S[ctx->j]);
return ctx->S[(ctx->S[ctx->i] + ctx->S[ctx->j]) % 256];
}
void void
arc4_crypt(struct arc4_ctx *ctx, arc4_crypt(struct arc4_ctx *ctx,
uint8_t *obuf, uint8_t const *ibuf, size_t buflen) uint8_t *obuf, uint8_t const *ibuf, size_t buflen)
{ {
int i = ctx->i;
int j = ctx->j;
size_t k; size_t k;
for (k = 0; k < buflen; k += 1) { for (k = 0; k < buflen; k += 1) {
uint8_t mask; obuf[k] = ibuf[k] ^ arc4_pad(ctx);
i = (i + 1) % 256;
j = (j + ctx->S[i]) % 256;
swap(ctx->S[i], ctx->S[j]);
mask = ctx->S[(ctx->S[i] + ctx->S[j]) % 256];
obuf[k] = ibuf[k] ^ mask;
} }
ctx->i = i;
ctx->j = j;
} }
void void

View File

@ -4,13 +4,10 @@
#include <stdint.h> #include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
struct arc4_ctx { struct arc4_ctx;
uint8_t S[256];
uint8_t i;
uint8_t j;
};
void arc4_init(struct arc4_ctx *ctx, uint8_t const *key, size_t keylen); void arc4_init(struct arc4_ctx *ctx, uint8_t const *key, size_t keylen);
uint8_t arc4_pad(struct arc4_ctx *ctx);
void arc4_crypt(struct arc4_ctx *ctx, void arc4_crypt(struct arc4_ctx *ctx,
uint8_t *obuf, uint8_t const *ibuf, size_t buflen); uint8_t *obuf, uint8_t const *ibuf, size_t buflen);
void arc4_crypt_buffer(uint8_t const *key, size_t keylen, void arc4_crypt_buffer(uint8_t const *key, size_t keylen,