2 * RC4 encryption/decryption/pseudo-random number generator
3 * Copyright (c) 2007 Reimar Doeffinger
5 * loosely based on LibTomCrypt by Tom St Denis
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 AVRC4 *av_rc4_alloc(void)
30 return av_mallocz(sizeof(struct AVRC4));
33 int av_rc4_init(AVRC4 *r, const uint8_t *key, int key_bits, int decrypt) {
36 uint8_t *state = r->state;
37 int keylen = key_bits >> 3;
39 return AVERROR(EINVAL);
40 for (i = 0; i < 256; i++)
44 for (j = 0, i = 0; i < 256; i++, j++) {
45 if (j == keylen) j = 0;
46 y += state[i] + key[j];
47 FFSWAP(uint8_t, state[i], state[y]);
54 void av_rc4_crypt(AVRC4 *r, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) {
55 uint8_t x = r->x, y = r->y;
56 uint8_t *state = r->state;
58 uint8_t sum = state[x] + state[y];
59 FFSWAP(uint8_t, state[x], state[y]);
60 *dst++ = src ? *src++ ^ state[sum] : state[sum];