Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
2.1 KiB

  1. // arc4.cpp - written and placed in the public domain by Wei Dai
  2. // The ARC4 algorithm was first revealed in an anonymous email to the
  3. // cypherpunks mailing list. This file originally contained some
  4. // code copied from this email. The code has since been rewritten in order
  5. // to clarify the copyright status of this file. It should now be
  6. // completely in the public domain.
  7. #include "pch.h"
  8. #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
  9. #include "arc4.h"
  10. NAMESPACE_BEGIN(CryptoPP)
  11. namespace Weak1 {
  12. void ARC4_TestInstantiations()
  13. {
  14. ARC4 x;
  15. }
  16. ARC4_Base::~ARC4_Base()
  17. {
  18. m_x = m_y = 0;
  19. }
  20. void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int keyLen, const NameValuePairs &params)
  21. {
  22. AssertValidKeyLength(keyLen);
  23. m_x = 1;
  24. m_y = 0;
  25. unsigned int i;
  26. for (i=0; i<256; i++)
  27. m_state[i] = i;
  28. unsigned int keyIndex = 0, stateIndex = 0;
  29. for (i=0; i<256; i++)
  30. {
  31. unsigned int a = m_state[i];
  32. stateIndex += key[keyIndex] + a;
  33. stateIndex &= 0xff;
  34. m_state[i] = m_state[stateIndex];
  35. m_state[stateIndex] = a;
  36. if (++keyIndex >= keyLen)
  37. keyIndex = 0;
  38. }
  39. int discardBytes = params.GetIntValueWithDefault("DiscardBytes", GetDefaultDiscardBytes());
  40. DiscardBytes(discardBytes);
  41. }
  42. template <class T>
  43. static inline unsigned int MakeByte(T &x, T &y, byte *s)
  44. {
  45. unsigned int a = s[x];
  46. y = (y+a) & 0xff;
  47. unsigned int b = s[y];
  48. s[x] = b;
  49. s[y] = a;
  50. x = (x+1) & 0xff;
  51. return s[(a+b) & 0xff];
  52. }
  53. void ARC4_Base::GenerateBlock(byte *output, size_t size)
  54. {
  55. while (size--)
  56. *output++ = MakeByte(m_x, m_y, m_state);
  57. }
  58. void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length)
  59. {
  60. if (length == 0)
  61. return;
  62. byte *const s = m_state;
  63. unsigned int x = m_x;
  64. unsigned int y = m_y;
  65. if (inString == outString)
  66. {
  67. do
  68. {
  69. *outString++ ^= MakeByte(x, y, s);
  70. } while (--length);
  71. }
  72. else
  73. {
  74. do
  75. {
  76. *outString++ = *inString++ ^ MakeByte(x, y, s);
  77. }
  78. while(--length);
  79. }
  80. m_x = x;
  81. m_y = y;
  82. }
  83. void ARC4_Base::DiscardBytes(size_t length)
  84. {
  85. if (length == 0)
  86. return;
  87. byte *const s = m_state;
  88. unsigned int x = m_x;
  89. unsigned int y = m_y;
  90. do
  91. {
  92. MakeByte(x, y, s);
  93. }
  94. while(--length);
  95. m_x = x;
  96. m_y = y;
  97. }
  98. }
  99. NAMESPACE_END