libcruft-crypto/block/tea.cpp

77 lines
2.1 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-2018 Danny Robson <danny@nerdcruft.net>
2018-01-14 17:17:34 +11:00
*/
#include "tea.hpp"
#include <cstdint>
#include <stdexcept>
using cruft::crypto::block::TEA;
///////////////////////////////////////////////////////////////////////////////
static const u32 MAGIC = 0x9E3779B9;
2018-01-14 17:17:34 +11:00
// each iteration performs two feistel rounds, for a total of 64
static const unsigned ITERATIONS = 32;
///////////////////////////////////////////////////////////////////////////////
TEA::TEA (key_t _key)
: m_key (_key)
2018-01-14 17:17:34 +11:00
{ ; }
///////////////////////////////////////////////////////////////////////////////
2018-01-14 17:17:34 +11:00
void
TEA::encrypt (cruft::view<word_t*> data)
2018-01-14 17:17:34 +11:00
{
if (data.size () % 2)
2018-01-14 17:17:34 +11:00
throw std::invalid_argument ("TEA requires even data count");
for (auto cursor = data.begin (), last = data.end (); cursor < last; ) {
word_t sum = 0;
word_t v0 = cursor[0];
word_t v1 = cursor[1];
2018-01-14 17:17:34 +11:00
for (unsigned i = 0; i < ITERATIONS; ++i) {
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]);
}
*cursor++ = v0;
*cursor++ = v1;
2018-01-14 17:17:34 +11:00
}
}
//-----------------------------------------------------------------------------
void
TEA::decrypt (cruft::view<word_t*> data)
2018-01-14 17:17:34 +11:00
{
if (data.size () % 2)
2018-01-14 17:17:34 +11:00
throw std::invalid_argument ("TEA requires even data count");
for (auto cursor = data.begin (), last = data.end (); cursor < last; ) {
word_t sum = MAGIC << 5;
word_t v0 = cursor[0];
word_t v1 = cursor[1];
2018-01-14 17:17:34 +11:00
for (unsigned i = 0; i < ITERATIONS; ++i) {
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;
}
*cursor++ = v0;
*cursor++ = v1;
2018-01-14 17:17:34 +11:00
}
}