rc4.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Copyright (c) 2017 Saleem Rashid
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included
  12. * in all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, E1PRESS
  15. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
  18. * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  19. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  20. * OTHER DEALINGS IN THE SOFTWARE.
  21. */
  22. #include "rc4.h"
  23. static inline void rc4_swap(RC4_CTX* ctx, uint8_t i, uint8_t j) {
  24. uint8_t temp = ctx->S[i];
  25. ctx->S[i] = ctx->S[j];
  26. ctx->S[j] = temp;
  27. }
  28. void rc4_init(RC4_CTX* ctx, const uint8_t* key, size_t length) {
  29. ctx->i = 0;
  30. ctx->j = 0;
  31. for(size_t i = 0; i < 256; i++) {
  32. ctx->S[i] = i;
  33. }
  34. uint8_t j = 0;
  35. for(size_t i = 0; i < 256; i++) {
  36. j += ctx->S[i] + key[i % length];
  37. rc4_swap(ctx, i, j);
  38. }
  39. }
  40. void rc4_encrypt(RC4_CTX* ctx, uint8_t* buffer, size_t length) {
  41. for(size_t idx = 0; idx < length; idx++) {
  42. ctx->i++;
  43. ctx->j += ctx->S[ctx->i];
  44. rc4_swap(ctx, ctx->i, ctx->j);
  45. uint8_t K = ctx->S[(ctx->S[ctx->i] + ctx->S[ctx->j]) % 256];
  46. buffer[idx] ^= K;
  47. }
  48. }