Migrate UI cleanup phase 4 from MIPS into ARM
[tomato.git] / release / src-rt-6.x.4708 / bcmcrypto / rc4.c
blob79eac24c18b95d952bb97fc8c3d6b4e07b66ba7f
1 /*
2 * rc4.c
3 * RC4 stream cipher
5 * Copyright (C) 2012, Broadcom Corporation
6 * All Rights Reserved.
7 *
8 * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation;
9 * the contents of this file may not be disclosed to third parties, copied
10 * or duplicated in any form, in whole or in part, without the prior
11 * written permission of Broadcom Corporation.
13 * $Id: rc4.c 241182 2011-02-17 21:50:03Z $
16 #include <typedefs.h>
17 #include <bcmcrypto/rc4.h>
19 void
20 BCMROMFN(prepare_key)(uint8 *key_data, int key_data_len, rc4_ks_t *ks)
22 unsigned int counter, index1 = 0, index2 = 0;
23 uint8 key_byte, temp;
24 uint8 *key_state = ks->state;
26 for (counter = 0; counter < RC4_STATE_NBYTES; counter++) {
27 key_state[counter] = (uint8) counter;
30 for (counter = 0; counter < RC4_STATE_NBYTES; counter++) {
31 key_byte = key_data[index1];
32 index2 = (key_byte + key_state[counter] + index2) % RC4_STATE_NBYTES;
33 temp = key_state[counter];
34 key_state[counter] = key_state[index2];
35 key_state[index2] = temp;
36 index1 = (index1 + 1) % key_data_len;
39 ks->x = 0;
40 ks->y = 0;
43 /* encrypt or decrypt using RC4 */
44 void
45 BCMROMFN(rc4)(uint8 *buf, int data_len, rc4_ks_t *ks)
47 uint8 tmp;
48 uint8 xor_ind, x = ks->x, y = ks->y, *key_state = ks->state;
49 int i;
51 for (i = 0; i < data_len; i++) {
52 y += key_state[++x]; /* mod RC4_STATE_NBYTES */
53 tmp = key_state[x];
54 key_state[x] = key_state[y];
55 key_state[y] = tmp;
56 xor_ind = key_state[x] + key_state[y];
57 buf[i] ^= key_state[xor_ind];
60 ks->x = x;
61 ks->y = y;
64 #ifdef BCMRC4_TEST
65 #include <stdio.h>
66 #include <string.h>
68 #include "rc4_vectors.h"
70 #define NUM_VECTORS (sizeof(rc4_vec) / sizeof(rc4_vec[0]))
72 int
73 main(int argc, char **argv)
75 int k, fail = 0;
76 uint8 data[RC4_STATE_NBYTES];
77 rc4_ks_t ks;
78 for (k = 0; k < NUM_VECTORS; k++) {
79 memset(data, 0, RC4_STATE_NBYTES);
80 memcpy(data, rc4_vec[k].input, rc4_vec[k].il);
82 prepare_key(rc4_vec[k].key, rc4_vec[k].kl, &ks);
83 rc4(data, rc4_vec[k].il, &ks);
84 if (memcmp(data, rc4_vec[k].ref, rc4_vec[k].il) != 0) {
85 printf("%s: rc4 encrypt failed\n", *argv);
86 fail++;
87 } else {
88 printf("%s: rc4 encrypt %d passed\n", *argv, k);
91 memset(data, 0, RC4_STATE_NBYTES);
92 memcpy(data, rc4_vec[k].ref, rc4_vec[k].il);
94 prepare_key(rc4_vec[k].key, rc4_vec[k].kl, &ks);
95 rc4(data, rc4_vec[k].il, &ks);
96 if (memcmp(data, rc4_vec[k].input, rc4_vec[k].il) != 0) {
97 printf("%s: rc4 decrypt failed\n", *argv);
98 fail++;
99 } else {
100 printf("%s: rc4 decrypt %d passed\n", *argv, k);
104 printf("%s: %s\n", *argv, fail?"FAILED":"PASSED");
105 return (fail);
107 #endif /* BCMRC4_TEST */