Tom Rini | 83d290c | 2018-05-06 17:58:06 -0400 | [diff] [blame] | 1 | // SPDX-License-Identifier: GPL-2.0+ |
Simon Glass | 1acab96 | 2015-06-23 15:39:07 -0600 | [diff] [blame] | 2 | /* |
| 3 | * (C) Copyright 2015 Google, Inc |
| 4 | * |
| 5 | * (C) Copyright 2008-2014 Rockchip Electronics |
| 6 | * |
| 7 | * Rivest Cipher 4 (RC4) implementation |
Simon Glass | 1acab96 | 2015-06-23 15:39:07 -0600 | [diff] [blame] | 8 | */ |
| 9 | |
Simon Glass | 1acab96 | 2015-06-23 15:39:07 -0600 | [diff] [blame] | 10 | #include <rc4.h> |
| 11 | |
John Keeping | 93a6e60 | 2022-11-18 16:13:17 +0000 | [diff] [blame] | 12 | void rc4_encode(unsigned char *buf, unsigned int len, const unsigned char key[16]) |
Simon Glass | 1acab96 | 2015-06-23 15:39:07 -0600 | [diff] [blame] | 13 | { |
| 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 | } |