Path: blob/a-new-beginning/SharedDependencies/Sources/cryptopp/arc4.cpp
2 views
// arc4.cpp - originally written and placed in the public domain by Wei Dai12// The ARC4 algorithm was first revealed in an anonymous email to the3// cypherpunks mailing list. This file originally contained some4// code copied from this email. The code has since been rewritten in order5// to clarify the copyright status of this file. It should now be6// completely in the public domain.78#include "pch.h"9#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 110#include "arc4.h"1112NAMESPACE_BEGIN(CryptoPP)13namespace Weak1 {1415#if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)16void ARC4_TestInstantiations()17{18ARC4 x;19}20#endif2122ARC4_Base::~ARC4_Base()23{24m_x = m_y = 0;25}2627void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)28{29AssertValidKeyLength(length);3031m_x = 1;32m_y = 0;3334unsigned int i;35for (i=0; i<256; i++)36m_state[i] = byte(i);3738unsigned int keyIndex = 0, stateIndex = 0;39for (i=0; i<256; i++)40{41unsigned int a = m_state[i];42stateIndex += key[keyIndex] + a;43stateIndex &= 0xff;44m_state[i] = m_state[stateIndex];45m_state[stateIndex] = byte(a);46if (++keyIndex >= length)47keyIndex = 0;48}4950int discardBytes = params.GetIntValueWithDefault("DiscardBytes", GetDefaultDiscardBytes());51DiscardBytes(discardBytes);52}5354template <class T>55static inline unsigned int MakeByte(T &x, T &y, byte *s)56{57unsigned int a = s[x];58y = byte((y+a) & 0xff);59unsigned int b = s[y];60s[x] = byte(b);61s[y] = byte(a);62x = byte((x+1) & 0xff);63return s[(a+b) & 0xff];64}6566void ARC4_Base::GenerateBlock(byte *output, size_t size)67{68while (size--)69*output++ = static_cast<byte>(MakeByte(m_x, m_y, m_state));70}7172void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length)73{74if (length == 0)75return;7677byte *const s = m_state;78unsigned int x = m_x;79unsigned int y = m_y;8081if (inString == outString)82{83do84{85*outString++ ^= MakeByte(x, y, s);86} while (--length);87}88else89{90do91{92*outString++ = *inString++ ^ byte(MakeByte(x, y, s));93}94while(--length);95}9697m_x = byte(x);98m_y = byte(y);99}100101void ARC4_Base::DiscardBytes(size_t n)102{103if (n == 0)104return;105106byte *const s = m_state;107unsigned int x = m_x;108unsigned int y = m_y;109110do111{112MakeByte(x, y, s);113}114while(--n);115116m_x = byte(x);117m_y = byte(y);118}119120}121NAMESPACE_END122123124