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

77 lines
2.3 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 "xtea.hpp"
using cruft::crypto::block::XTEA;
///////////////////////////////////////////////////////////////////////////////
static const uint32_t 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;
///////////////////////////////////////////////////////////////////////////////
XTEA::XTEA (key_t _key):
m_key (_key)
{ }
//-----------------------------------------------------------------------------
void
XTEA::encrypt (cruft::view<word_t*> dst, cruft::view<word_t const*> src)
2018-01-14 17:17:34 +11:00
{
if (dst.size () != src.size ())
throw std::invalid_argument ("mismatching encode/decode buffer sizes");
if (src.size () % 2)
2018-01-14 17:17:34 +11:00
throw std::invalid_argument ("XTEA requires even data count");
for (size_t i = 0, last = src.size (); i != last; i += 2) {
2018-01-14 17:17:34 +11:00
uint32_t sum = 0;
uint32_t v0 = src[i + 0];
uint32_t v1 = src[i + 1];
2018-01-14 17:17:34 +11:00
for (unsigned j = 0; j < ITERATIONS; ++j) {
2018-01-14 17:17:34 +11:00
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + m_key[sum & 3]);
sum += MAGIC;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + m_key[(sum >> 11) & 3]);
}
dst[i + 0] = v0;
dst[i + 1] = v1;
2018-01-14 17:17:34 +11:00
}
}
//-----------------------------------------------------------------------------
void
XTEA::decrypt (cruft::view<word_t*> dst, cruft::view<word_t const*> src)
2018-01-14 17:17:34 +11:00
{
if (dst.size () != src.size ())
throw std::invalid_argument ("mismatching encode/decode buffer sizes");
if (src.size () % 2)
2018-01-14 17:17:34 +11:00
throw std::invalid_argument ("XTEA requires even data count");
for (size_t i = 0, last = src.size (); i != last; i += 2) {
2018-01-14 17:17:34 +11:00
uint32_t sum = ITERATIONS * MAGIC;
uint32_t v0 = src[i + 0];
uint32_t v1 = src[i + 1];
2018-01-14 17:17:34 +11:00
for (unsigned j = 0; j < ITERATIONS; ++j) {
2018-01-14 17:17:34 +11:00
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + m_key[(sum >> 11) & 3]);
sum -= MAGIC;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + m_key[sum & 3]);
}
dst[i + 0] = v0;
dst[i + 1] = v1;
2018-01-14 17:17:34 +11:00
}
}