blob: 3839924a2b2c7790dc8cb596c7409e32f698e671 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
Simon Glass1acab962015-06-23 15:39:07 -06002/*
3 * (C) Copyright 2015 Google, Inc
4 *
5 * (C) Copyright 2008-2014 Rockchip Electronics
6 *
7 * Rivest Cipher 4 (RC4) implementation
Simon Glass1acab962015-06-23 15:39:07 -06008 */
9
Simon Glass1acab962015-06-23 15:39:07 -060010#include <rc4.h>
11
John Keeping93a6e602022-11-18 16:13:17 +000012void rc4_encode(unsigned char *buf, unsigned int len, const unsigned char key[16])
Simon Glass1acab962015-06-23 15:39:07 -060013{
14 unsigned char s[256], k[256], temp;
15 unsigned short i, j, t;
16 int ptr;
17
18 j = 0;
19 for (i = 0; i < 256; i++) {
20 s[i] = (unsigned char)i;
21 j &= 0x0f;
22 k[i] = key[j];
23 j++;
24 }
25
26 j = 0;
27 for (i = 0; i < 256; i++) {
28 j = (j + s[i] + k[i]) % 256;
29 temp = s[i];
30 s[i] = s[j];
31 s[j] = temp;
32 }
33
34 i = 0;
35 j = 0;
36 for (ptr = 0; ptr < len; ptr++) {
37 i = (i + 1) % 256;
38 j = (j + s[i]) % 256;
39 temp = s[i];
40 s[i] = s[j];
41 s[j] = temp;
42 t = (s[i] + (s[j] % 256)) % 256;
43 buf[ptr] = buf[ptr] ^ s[t];
44 }
45}