9
3

RC4.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator 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. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "RC4.h"
  17. #include <string.h>
  18. static bool g_bInitStateInitialized = false;
  19. static uchar g_byInitState[256];
  20. RC4::RC4(int64 nKey)
  21. {
  22. if( !g_bInitStateInitialized )
  23. {
  24. for(int16 i = 0; i < 256; i++ )
  25. g_byInitState[i] = i;
  26. }
  27. Init(nKey);
  28. }
  29. RC4::~RC4()
  30. {
  31. }
  32. void RC4::Init(int64 nKey)
  33. {
  34. memcpy(m_state, g_byInitState, 256);
  35. m_x = 0;
  36. m_y = 0;
  37. ulong dwKeyIndex = 0;
  38. ulong dwStateIndex = 0;
  39. uchar* pKey = (uchar*)&nKey;
  40. for(int16 i = 0; i < 256; i++ )
  41. {
  42. ulong dwTemp = m_state[i];
  43. dwStateIndex += pKey[dwKeyIndex] + dwTemp;
  44. dwStateIndex &= 0xFF;
  45. m_state[i] = m_state[dwStateIndex];
  46. m_state[dwStateIndex] = (uchar)dwTemp;
  47. dwKeyIndex++;
  48. dwKeyIndex &= 7;
  49. }
  50. }
  51. // A = m_state[X + 1]
  52. // B = m_state[Y + A]
  53. // C ^= m_state[(A + B)]
  54. // X = 20
  55. // Y = ?
  56. // C = 0
  57. // m_state[(A + B)] = Cypher Byte
  58. void RC4::Cypher(uchar* pBuffer, int32 nLength)
  59. {
  60. int32 nOffset = 0;
  61. uchar byKey1 = m_x;
  62. uchar byKey2 = m_y;
  63. if( nLength > 0 )
  64. {
  65. do
  66. {
  67. byKey1++;
  68. uchar byKeyVal1 = m_state[byKey1];
  69. byKey2 += byKeyVal1;
  70. uchar byKeyVal2 = m_state[byKey2];
  71. m_state[byKey1] = byKeyVal2;
  72. m_state[byKey2] = byKeyVal1;
  73. pBuffer[nOffset++] ^= m_state[(byKeyVal1 + byKeyVal2) & 0xFF];
  74. } while( nOffset < nLength );
  75. }
  76. m_x = byKey1;
  77. m_y = byKey2;
  78. }