/* * 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 */ #include "xtea.hpp" using cruft::crypto::block::XTEA; /////////////////////////////////////////////////////////////////////////////// static const u32 MAGIC = 0x9E3779B9; // 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 data) { if (data.size () % 2) throw std::invalid_argument ("XTEA requires even data count"); for (auto cursor = data.begin (), last = data.end (); cursor < last; ) { uint32_t sum = 0; uint32_t v0 = cursor[0]; uint32_t v1 = cursor[1]; for (unsigned i = 0; i < ITERATIONS; ++i) { 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]); } *cursor++ = v0; *cursor++ = v1; } } //----------------------------------------------------------------------------- void XTEA::decrypt (cruft::view data) { if (data.size () % 2) throw std::invalid_argument ("XTEA requires even data count"); for (auto cursor = data.begin (), last = data.end (); cursor < last; ) { uint32_t sum = ITERATIONS * MAGIC; uint32_t v0 = cursor[0]; uint32_t v1 = cursor[1]; for (unsigned i = 0; i < ITERATIONS; ++i) { 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]); } *cursor++ = v0; *cursor++ = v1; } }