5 * Copyright (C) 2012, Broadcom Corporation
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 $
17 #include <bcmcrypto/rc4.h>
20 BCMROMFN(prepare_key
)(uint8
*key_data
, int key_data_len
, rc4_ks_t
*ks
)
22 unsigned int counter
, index1
= 0, index2
= 0;
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
;
43 /* encrypt or decrypt using RC4 */
45 BCMROMFN(rc4
)(uint8
*buf
, int data_len
, rc4_ks_t
*ks
)
48 uint8 xor_ind
, x
= ks
->x
, y
= ks
->y
, *key_state
= ks
->state
;
51 for (i
= 0; i
< data_len
; i
++) {
52 y
+= key_state
[++x
]; /* mod RC4_STATE_NBYTES */
54 key_state
[x
] = key_state
[y
];
56 xor_ind
= key_state
[x
] + key_state
[y
];
57 buf
[i
] ^= key_state
[xor_ind
];
68 #include "rc4_vectors.h"
70 #define NUM_VECTORS (sizeof(rc4_vec) / sizeof(rc4_vec[0]))
73 main(int argc
, char **argv
)
76 uint8 data
[RC4_STATE_NBYTES
];
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
);
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
);
100 printf("%s: rc4 decrypt %d passed\n", *argv
, k
);
104 printf("%s: %s\n", *argv
, fail
?"FAILED":"PASSED");
107 #endif /* BCMRC4_TEST */