rc4.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. ** Command & Conquer Renegade(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. //
  19. // rc4.cpp
  20. // RC4 encryption / decryption
  21. //
  22. #include "rc4.h"
  23. #include <memory.h>
  24. static unsigned char RC4_Temp_Byte;
  25. #define RC4_SWAP_BYTE(a,b) RC4_Temp_Byte=a; a=b; b=RC4_Temp_Byte
  26. //
  27. // Don't rely on this to zero the key
  28. //
  29. RC4Class::RC4Class()
  30. {
  31. memset(Key.State, 0, 256);
  32. Key.X=0;
  33. Key.Y=0;
  34. }
  35. //
  36. // Setup the encryption key. This must be called before you encrypt/decrypt!
  37. //
  38. void RC4Class::Prepare_Key(const unsigned char *key_data_ptr, int key_data_len)
  39. {
  40. unsigned char index1;
  41. unsigned char index2;
  42. unsigned char *state;
  43. int counter;
  44. state = &Key.State[0];
  45. for (counter = 0; counter < 256; counter++)
  46. state[counter] = (unsigned char)counter;
  47. Key.X = 0;
  48. Key.Y = 0;
  49. index1 = 0;
  50. index2 = 0;
  51. for (counter = 0; counter < 256; counter++) {
  52. index2 = (unsigned char)(key_data_ptr[index1] + state[counter] + index2);
  53. RC4_SWAP_BYTE(state[counter], state[index2]);
  54. index1 = (unsigned char)((index1 + 1) % key_data_len);
  55. }
  56. }
  57. //
  58. // RC4 in standard mode.
  59. //
  60. // This will XOR the buffer with the RC4 stream (like a one time pad).
  61. //
  62. void RC4Class::RC4(unsigned char *buffer_ptr, int buffer_len)
  63. {
  64. unsigned char x;
  65. unsigned char y;
  66. unsigned char *state;
  67. int counter;
  68. x = Key.X;
  69. y = Key.Y;
  70. state = &Key.State[0];
  71. for (counter = 0; counter < buffer_len; counter++) {
  72. x++;
  73. y = (unsigned char)(y + state[x]);
  74. RC4_SWAP_BYTE(state[x], state[y]);
  75. buffer_ptr[counter] ^= state[(state[x] + state[y]) & 255];
  76. }
  77. Key.X = x;
  78. Key.Y = y;
  79. }