yading@11: /* yading@11: * RC4 encryption/decryption/pseudo-random number generator yading@11: * Copyright (c) 2007 Reimar Doeffinger yading@11: * yading@11: * loosely based on LibTomCrypt by Tom St Denis yading@11: * yading@11: * This file is part of FFmpeg. yading@11: * yading@11: * FFmpeg is free software; you can redistribute it and/or yading@11: * modify it under the terms of the GNU Lesser General Public yading@11: * License as published by the Free Software Foundation; either yading@11: * version 2.1 of the License, or (at your option) any later version. yading@11: * yading@11: * FFmpeg is distributed in the hope that it will be useful, yading@11: * but WITHOUT ANY WARRANTY; without even the implied warranty of yading@11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU yading@11: * Lesser General Public License for more details. yading@11: * yading@11: * You should have received a copy of the GNU Lesser General Public yading@11: * License along with FFmpeg; if not, write to the Free Software yading@11: * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA yading@11: */ yading@11: #include "avutil.h" yading@11: #include "common.h" yading@11: #include "rc4.h" yading@11: yading@11: typedef struct AVRC4 AVRC4; yading@11: yading@11: int av_rc4_init(AVRC4 *r, const uint8_t *key, int key_bits, int decrypt) { yading@11: int i, j; yading@11: uint8_t y; yading@11: uint8_t *state = r->state; yading@11: int keylen = key_bits >> 3; yading@11: if (key_bits & 7) yading@11: return -1; yading@11: for (i = 0; i < 256; i++) yading@11: state[i] = i; yading@11: y = 0; yading@11: // j is i % keylen yading@11: for (j = 0, i = 0; i < 256; i++, j++) { yading@11: if (j == keylen) j = 0; yading@11: y += state[i] + key[j]; yading@11: FFSWAP(uint8_t, state[i], state[y]); yading@11: } yading@11: r->x = 1; yading@11: r->y = state[1]; yading@11: return 0; yading@11: } yading@11: yading@11: void av_rc4_crypt(AVRC4 *r, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) { yading@11: uint8_t x = r->x, y = r->y; yading@11: uint8_t *state = r->state; yading@11: while (count-- > 0) { yading@11: uint8_t sum = state[x] + state[y]; yading@11: FFSWAP(uint8_t, state[x], state[y]); yading@11: *dst++ = src ? *src++ ^ state[sum] : state[sum]; yading@11: x++; yading@11: y += state[x]; yading@11: } yading@11: r->x = x; r->y = y; yading@11: }