monotone

monotone Mtn Source Tree

Root/cryptopp/arc4.cpp

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

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status