rc4.c 825 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * (C) Copyright 2015 Google, Inc
  3. *
  4. * (C) Copyright 2008-2014 Rockchip Electronics
  5. *
  6. * Rivest Cipher 4 (RC4) implementation
  7. *
  8. * SPDX-License-Identifier: GPL-2.0+
  9. */
  10. #ifndef USE_HOSTCC
  11. #include <common.h>
  12. #endif
  13. #include <rc4.h>
  14. void rc4_encode(unsigned char *buf, unsigned int len, unsigned char key[16])
  15. {
  16. unsigned char s[256], k[256], temp;
  17. unsigned short i, j, t;
  18. int ptr;
  19. j = 0;
  20. for (i = 0; i < 256; i++) {
  21. s[i] = (unsigned char)i;
  22. j &= 0x0f;
  23. k[i] = key[j];
  24. j++;
  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. i = 0;
  34. j = 0;
  35. for (ptr = 0; ptr < len; ptr++) {
  36. i = (i + 1) % 256;
  37. j = (j + s[i]) % 256;
  38. temp = s[i];
  39. s[i] = s[j];
  40. s[j] = temp;
  41. t = (s[i] + (s[j] % 256)) % 256;
  42. buf[ptr] = buf[ptr] ^ s[t];
  43. }
  44. }