rc4.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * RC4 encryption/decryption/pseudo-random number generator
  3. * Copyright (c) 2007 Reimar Doeffinger
  4. *
  5. * loosely based on LibTomCrypt by Tom St Denis
  6. *
  7. * This file is part of FFmpeg.
  8. *
  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.
  13. *
  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.
  18. *
  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
  22. */
  23. #include "avutil.h"
  24. #include "common.h"
  25. #include "rc4.h"
  26. typedef struct AVRC4 AVRC4;
  27. int av_rc4_init(AVRC4 *r, const uint8_t *key, int key_bits, int decrypt) {
  28. int i, j;
  29. uint8_t y;
  30. uint8_t *state = r->state;
  31. int keylen = key_bits >> 3;
  32. if (key_bits & 7)
  33. return -1;
  34. for (i = 0; i < 256; i++)
  35. state[i] = i;
  36. y = 0;
  37. // j is i % keylen
  38. for (j = 0, i = 0; i < 256; i++, j++) {
  39. if (j == keylen) j = 0;
  40. y += state[i] + key[j];
  41. FFSWAP(uint8_t, state[i], state[y]);
  42. }
  43. r->x = 1;
  44. r->y = state[1];
  45. return 0;
  46. }
  47. void av_rc4_crypt(AVRC4 *r, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) {
  48. uint8_t x = r->x, y = r->y;
  49. uint8_t *state = r->state;
  50. while (count-- > 0) {
  51. uint8_t sum = state[x] + state[y];
  52. FFSWAP(uint8_t, state[x], state[y]);
  53. *dst++ = src ? *src++ ^ state[sum] : state[sum];
  54. x++;
  55. y += state[x];
  56. }
  57. r->x = x; r->y = y;
  58. }
  59. #if LIBAVUTIL_VERSION_MAJOR < 50
  60. void ff_rc4_enc(const uint8_t *key, int keylen, uint8_t *data, int datalen) {
  61. AVRC4 r;
  62. av_rc4_init(&r, key, keylen * 8, 0);
  63. av_rc4_crypt(&r, data, data, datalen, NULL, 0);
  64. }
  65. #endif