libcruft-crypto/stream/rc4.cpp

59 lines
1.2 KiB
C++
Raw Normal View History

2018-01-14 17:17:34 +11:00
/*
2018-08-04 15:18:16 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
2018-01-14 17:17:34 +11:00
*
* Copyright 2015 Danny Robson <danny@nerdcruft.net>
*/
#include "rc4.hpp"
#include <algorithm>
#include <numeric>
using cruft::crypto::stream::RC4;
///////////////////////////////////////////////////////////////////////////////
RC4::RC4 (const uint8_t *restrict key, size_t len):
x (0),
y (0)
{
std::iota (S.begin (), S.end (), 0);
for (size_t i = 0, j = 0; i < 256; ++i) {
j = (j + S[i] + key[i % len]) % 256;
std::swap (S[i], S[j]);
}
}
//-----------------------------------------------------------------------------
void
RC4::discard (size_t len)
{
while (len--)
get ();
}
//-----------------------------------------------------------------------------
void
RC4::generate (uint8_t *restrict dst, size_t len)
{
std::generate_n (dst, len, [this] (void) { return get (); });
}
//-----------------------------------------------------------------------------
uint8_t
RC4::get (void)
{
x = (x + 1) % 256;
y = (y + S[x]) % 256;
std::swap (S[x], S[y]);
return S[(S[x] + S[y]) % 256];
}