You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.0KB

  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 Libav.
  8. *
  9. * Libav 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. * Libav 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 Libav; 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 "mem.h"
  26. #include "rc4.h"
  27. #if !FF_API_CRYPTO_CONTEXT
  28. struct AVRC4 {
  29. uint8_t state[256];
  30. int x, y;
  31. };
  32. #endif
  33. AVRC4 *av_rc4_alloc(void)
  34. {
  35. return av_mallocz(sizeof(struct AVRC4));
  36. }
  37. int av_rc4_init(AVRC4 *r, const uint8_t *key, int key_bits, int decrypt) {
  38. int i, j;
  39. uint8_t y;
  40. uint8_t *state = r->state;
  41. int keylen = key_bits >> 3;
  42. if (key_bits & 7)
  43. return -1;
  44. for (i = 0; i < 256; i++)
  45. state[i] = i;
  46. y = 0;
  47. // j is i % keylen
  48. for (j = 0, i = 0; i < 256; i++, j++) {
  49. if (j == keylen) j = 0;
  50. y += state[i] + key[j];
  51. FFSWAP(uint8_t, state[i], state[y]);
  52. }
  53. r->x = 1;
  54. r->y = state[1];
  55. return 0;
  56. }
  57. void av_rc4_crypt(AVRC4 *r, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) {
  58. uint8_t x = r->x, y = r->y;
  59. uint8_t *state = r->state;
  60. while (count-- > 0) {
  61. uint8_t sum = state[x] + state[y];
  62. FFSWAP(uint8_t, state[x], state[y]);
  63. *dst++ = src ? *src++ ^ state[sum] : state[sum];
  64. x++;
  65. y += state[x];
  66. }
  67. r->x = x; r->y = y;
  68. }