xref: /openbmc/u-boot/lib/rc4.c (revision b9553986)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2015 Google, Inc
4  *
5  * (C) Copyright 2008-2014 Rockchip Electronics
6  *
7  * Rivest Cipher 4 (RC4) implementation
8  */
9 
10 #ifndef USE_HOSTCC
11 #include <common.h>
12 #endif
13 #include <rc4.h>
14 
15 void rc4_encode(unsigned char *buf, unsigned int len, unsigned char key[16])
16 {
17 	unsigned char s[256], k[256], temp;
18 	unsigned short i, j, t;
19 	int ptr;
20 
21 	j = 0;
22 	for (i = 0; i < 256; i++) {
23 		s[i] = (unsigned char)i;
24 		j &= 0x0f;
25 		k[i] = key[j];
26 		j++;
27 	}
28 
29 	j = 0;
30 	for (i = 0; i < 256; i++) {
31 		j = (j + s[i] + k[i]) % 256;
32 		temp = s[i];
33 		s[i] = s[j];
34 		s[j] = temp;
35 	}
36 
37 	i = 0;
38 	j = 0;
39 	for (ptr = 0; ptr < len; ptr++) {
40 		i = (i + 1) % 256;
41 		j = (j + s[i]) % 256;
42 		temp = s[i];
43 		s[i] = s[j];
44 		s[j] = temp;
45 		t = (s[i] + (s[j] % 256)) % 256;
46 		buf[ptr] = buf[ptr] ^ s[t];
47 	}
48 }
49