1
// salsa.cpp - written and placed in the public domain by Wei Dai
8
NAMESPACE_BEGIN(CryptoPP)
10
void Salsa20_TestInstantiations()
12
Salsa20::Encryption x;
15
void Salsa20_Policy::GetNextIV(byte *IV) const
17
word32 j6 = m_state[6] + 1;
18
word32 j7 = m_state[7] + (j6 == 0);
20
UnalignedPutWord(LITTLE_ENDIAN_ORDER, IV, j6);
21
UnalignedPutWord(LITTLE_ENDIAN_ORDER, IV+4, j7);
24
void Salsa20_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
26
m_rounds = params.GetIntValueWithDefault(Name::Rounds(), 20);
28
if (!(m_rounds == 8 || m_rounds == 12 || m_rounds == 20))
29
throw InvalidRounds(StaticAlgorithmName(), m_rounds);
31
GetUserKey(LITTLE_ENDIAN_ORDER, m_state+1, 4, key, 16);
32
GetUserKey(LITTLE_ENDIAN_ORDER, m_state+11, 4, key + length - 16, 16);
34
// m_state[0,5,10,15] forms "expand 16-byte k" or "expand 32-byte k"
35
m_state[0] = 0x61707865;
36
m_state[5] = (length == 16) ? 0x3120646e : 0x3320646e;
37
m_state[10] = (length == 16) ? 0x79622d36 : 0x79622d32;
38
m_state[15] = 0x6b206574;
41
void Salsa20_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV)
43
GetUserKey(LITTLE_ENDIAN_ORDER, m_state+6, 4, IV, 8);
46
void Salsa20_Policy::SeekToIteration(lword iterationCount)
48
m_state[8] = (word32)iterationCount;
49
m_state[9] = (word32)SafeRightShift<32>(iterationCount);
52
void Salsa20_Policy::OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
54
KeystreamOutput<LittleEndian> keystreamOutput(operation, output, input);
56
word32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
57
word32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
76
for (size_t iteration = 0; iteration < iterationCount; ++iteration)
95
for (int i=m_rounds; i>0; i-=2)
97
#define QUARTER_ROUND(a, b, c, d) \
98
b = b ^ rotlFixed(a + d, 7); \
99
c = c ^ rotlFixed(b + a, 9); \
100
d = d ^ rotlFixed(c + b, 13); \
101
a = a ^ rotlFixed(d + c, 18);
103
QUARTER_ROUND(x0, x4, x8, x12)
104
QUARTER_ROUND(x5, x9, x13, x1)
105
QUARTER_ROUND(x10, x14, x2, x6)
106
QUARTER_ROUND(x15, x3, x7, x11)
108
QUARTER_ROUND(x0, x1, x2, x3)
109
QUARTER_ROUND(x5, x6, x7, x4)
110
QUARTER_ROUND(x10, x11, x8, x9)
111
QUARTER_ROUND(x15, x12, x13, x14)
114
keystreamOutput (x0 + j0)