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