/* * 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/. * * Copyright 2015 Danny Robson */ #include "rc4.hpp" #include #include 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]; }