libcruft-crypto/cruft/crypto/block/tea.cpp

81 lines
2.3 KiB
C++

/*
* 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-2018 Danny Robson <danny@nerdcruft.net>
*/
#include "tea.hpp"
#include <cstdint>
#include <stdexcept>
using cruft::crypto::block::TEA;
///////////////////////////////////////////////////////////////////////////////
static u32 constexpr MAGIC = 0x9E3779B9;
static int constexpr ITERATIONS = 64;
///////////////////////////////////////////////////////////////////////////////
TEA::TEA (key_t _key)
: m_key (_key)
{ ; }
///////////////////////////////////////////////////////////////////////////////
void
TEA::encrypt (cruft::view<word_t*> dst, cruft::view<word_t const*> src)
{
if (dst.size () != src.size ())
throw std::invalid_argument ("mismatching encode/decode buffer sizes");
if (src.size () % 2)
throw std::invalid_argument ("TEA requires even data count");
for (size_t i = 0, last = src.size (); i < last; i += 2) {
word_t sum = 0;
word_t v0 = src[i + 0];
word_t v1 = src[i + 1];
for (int j = 0; j < ITERATIONS; j += 2) {
sum += MAGIC;
v0 += ((v1 << 4) + m_key[0]) ^ (v1 + sum) ^ ((v1 >> 5) + m_key[1]);
v1 += ((v0 << 4) + m_key[2]) ^ (v0 + sum) ^ ((v0 >> 5) + m_key[3]);
}
dst[i + 0] = v0;
dst[i + 1] = v1;
}
}
//-----------------------------------------------------------------------------
void
TEA::decrypt (cruft::view<word_t*> dst, cruft::view<word_t const*> src)
{
if (dst.size () != src.size ())
throw std::invalid_argument ("mismatching encode/decode buffer sizes");
if (src.size () % 2)
throw std::invalid_argument ("TEA requires even data count");
for (size_t i = 0, last = src.size (); i < last; i += 2) {
word_t sum = MAGIC << 5;
word_t v0 = src[i + 0];
word_t v1 = src[i + 1];
for (int j = 0; j < ITERATIONS; j += 2) {
v1 -= ((v0 << 4) + m_key[2]) ^ (v0 + sum) ^ ((v0 >> 5) + m_key[3]);
v0 -= ((v1 << 4) + m_key[0]) ^ (v1 + sum) ^ ((v1 >> 5) + m_key[1]);
sum -= MAGIC;
}
dst[i + 0] = v0;
dst[i + 1] = v1;
}
}