rc4.c 822 B

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