Skip to content

Instantly share code, notes, and snippets.

@kugland
Last active July 28, 2019 18:41
Show Gist options
  • Save kugland/fa691e74cacb3a48a8442821156c1dd3 to your computer and use it in GitHub Desktop.
Save kugland/fa691e74cacb3a48a8442821156c1dd3 to your computer and use it in GitHub Desktop.
RC4 algorithm for microcontrollers
#include "micro_rc4.h"
static char rc4_state[256];
static unsigned char rc4_i, rc4_j;
__attribute__((always_inline)) inline
static void rc4_swap(void)
{
unsigned char rc4_tmp = rc4_state[rc4_i];
rc4_state[rc4_i] = rc4_state[rc4_j];
rc4_state[rc4_j] = rc4_tmp;
}
void rc4_init(const char *key, unsigned char len)
{
rc4_i = 0;
do rc4_state[rc4_i] = rc4_i;
while (++rc4_i != 0);
rc4_i = rc4_j = 0;
do {
rc4_j += rc4_state[rc4_i] + key[rc4_i % len];
rc4_swap();
} while (++rc4_i != 0);
rc4_i = rc4_j = 0;
}
char rc4_next()
{
rc4_i++;
rc4_j += rc4_state[rc4_i];
rc4_swap();
return rc4_state[(rc4_state[rc4_i] + rc4_state[rc4_j]) & 255];
}
#ifndef MICRO_RC4_H_DDCF63B50CD9256B03223D3F947427E50DE494A5
#define MICRO_RC4_H_DDCF63B50CD9256B03223D3F947427E50DE494A5
#include <limits.h>
#if CHAR_BIT != 8
#error CHAR_BIT != 8 not supported
#endif
void rc4_init(const char *key, unsigned char len);
char rc4_next();
#endif /* MICRO_RC4_H_DDCF63B50CD9256B03223D3F947427E50DE494A5 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment