00001
00002
00003
00004
00005
00006
00007
00008
00009 #include "pch.h"
00010 #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
00011 #include "arc4.h"
00012
00013 NAMESPACE_BEGIN(CryptoPP)
00014 namespace Weak1 {
00015
00016 #if !defined(NDEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
00017 void ARC4_TestInstantiations()
00018 {
00019 ARC4 x;
00020 }
00021 #endif
00022
00023 ARC4_Base::~ARC4_Base()
00024 {
00025 m_x = m_y = 0;
00026 }
00027
00028 void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int keyLen, const NameValuePairs ¶ms)
00029 {
00030 AssertValidKeyLength(keyLen);
00031
00032 m_x = 1;
00033 m_y = 0;
00034
00035 unsigned int i;
00036 for (i=0; i<256; i++)
00037 m_state[i] = byte(i);
00038
00039 unsigned int keyIndex = 0, stateIndex = 0;
00040 for (i=0; i<256; i++)
00041 {
00042 unsigned int a = m_state[i];
00043 stateIndex += key[keyIndex] + a;
00044 stateIndex &= 0xff;
00045 m_state[i] = m_state[stateIndex];
00046 m_state[stateIndex] = byte(a);
00047 if (++keyIndex >= keyLen)
00048 keyIndex = 0;
00049 }
00050
00051 int discardBytes = params.GetIntValueWithDefault("DiscardBytes", GetDefaultDiscardBytes());
00052 DiscardBytes(discardBytes);
00053 }
00054
00055 template <class T>
00056 static inline unsigned int MakeByte(T &x, T &y, byte *s)
00057 {
00058 unsigned int a = s[x];
00059 y = byte((y+a) & 0xff);
00060 unsigned int b = s[y];
00061 s[x] = byte(b);
00062 s[y] = byte(a);
00063 x = byte((x+1) & 0xff);
00064 return s[(a+b) & 0xff];
00065 }
00066
00067 void ARC4_Base::GenerateBlock(byte *output, size_t size)
00068 {
00069 while (size--)
00070 *output++ = static_cast<byte>(MakeByte(m_x, m_y, m_state));
00071 }
00072
00073 void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length)
00074 {
00075 if (length == 0)
00076 return;
00077
00078 byte *const s = m_state;
00079 unsigned int x = m_x;
00080 unsigned int y = m_y;
00081
00082 if (inString == outString)
00083 {
00084 do
00085 {
00086 *outString++ ^= MakeByte(x, y, s);
00087 } while (--length);
00088 }
00089 else
00090 {
00091 do
00092 {
00093 *outString++ = *inString++ ^ byte(MakeByte(x, y, s));
00094 }
00095 while(--length);
00096 }
00097
00098 m_x = byte(x);
00099 m_y = byte(y);
00100 }
00101
00102 void ARC4_Base::DiscardBytes(size_t length)
00103 {
00104 if (length == 0)
00105 return;
00106
00107 byte *const s = m_state;
00108 unsigned int x = m_x;
00109 unsigned int y = m_y;
00110
00111 do
00112 {
00113 MakeByte(x, y, s);
00114 }
00115 while(--length);
00116
00117 m_x = byte(x);
00118 m_y = byte(y);
00119 }
00120
00121 }
00122 NAMESPACE_END