diff options
Diffstat (limited to 'tests/arc4.c')
| -rw-r--r-- | tests/arc4.c | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/tests/arc4.c b/tests/arc4.c new file mode 100644 index 0000000..b033cc6 --- /dev/null +++ b/tests/arc4.c | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | #include <stdint.h> | ||
| 2 | #include "tests/arc4.h" | ||
| 3 | |||
| 4 | /* Swap bytes. */ | ||
| 5 | static inline void | ||
| 6 | swap_byte (uint8_t *a, uint8_t *b) | ||
| 7 | { | ||
| 8 | uint8_t t = *a; | ||
| 9 | *a = *b; | ||
| 10 | *b = t; | ||
| 11 | } | ||
| 12 | |||
| 13 | void | ||
| 14 | arc4_init (struct arc4 *arc4, const void *key_, size_t size) | ||
| 15 | { | ||
| 16 | const uint8_t *key = key_; | ||
| 17 | size_t key_idx; | ||
| 18 | uint8_t *s; | ||
| 19 | int i, j; | ||
| 20 | |||
| 21 | s = arc4->s; | ||
| 22 | arc4->i = arc4->j = 0; | ||
| 23 | for (i = 0; i < 256; i++) | ||
| 24 | s[i] = i; | ||
| 25 | for (key_idx = 0, i = j = 0; i < 256; i++) | ||
| 26 | { | ||
| 27 | j = (j + s[i] + key[key_idx]) & 255; | ||
| 28 | swap_byte (s + i, s + j); | ||
| 29 | if (++key_idx >= size) | ||
| 30 | key_idx = 0; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | void | ||
| 35 | arc4_crypt (struct arc4 *arc4, void *buf_, size_t size) | ||
| 36 | { | ||
| 37 | uint8_t *buf = buf_; | ||
| 38 | uint8_t *s; | ||
| 39 | uint8_t i, j; | ||
| 40 | |||
| 41 | s = arc4->s; | ||
| 42 | i = arc4->i; | ||
| 43 | j = arc4->j; | ||
| 44 | while (size-- > 0) | ||
| 45 | { | ||
| 46 | i += 1; | ||
| 47 | j += s[i]; | ||
| 48 | swap_byte (s + i, s + j); | ||
| 49 | *buf++ ^= s[(s[i] + s[j]) & 255]; | ||
| 50 | } | ||
| 51 | arc4->i = i; | ||
| 52 | arc4->j = j; | ||
| 53 | } | ||
