xtea.cpp

main 76 lines · 2.6 KB Raw
Alex Alex Commit Server upload 18/10/2026 23:38
1/**
2 * The Forgotten Server - a free and open-source MMORPG server emulator
3 * Copyright (C) 2020 Mark Samman <mark.samman@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#include "otpch.h"
21
22#include "xtea.h"
23
24#include <array>
25#include <assert.h>
26
27namespace xtea {
28
29namespace {
30
31constexpr uint32_t delta = 0x9E3779B9;
32
33template<typename Round>
34void apply_rounds(uint8_t* data, size_t length, Round round)
35{
36 for (auto j = 0u; j < length; j += 8) {
37 uint32_t left = data[j+0] | data[j+1] << 8u | data[j+2] << 16u | data[j+3] << 24u,
38 right = data[j+4] | data[j+5] << 8u | data[j+6] << 16u | data[j+7] << 24u;
39
40 round(left, right);
41
42 data[j] = static_cast<uint8_t>(left);
43 data[j+1] = static_cast<uint8_t>(left >> 8u);
44 data[j+2] = static_cast<uint8_t>(left >> 16u);
45 data[j+3] = static_cast<uint8_t>(left >> 24u);
46 data[j+4] = static_cast<uint8_t>(right);
47 data[j+5] = static_cast<uint8_t>(right >> 8u);
48 data[j+6] = static_cast<uint8_t>(right >> 16u);
49 data[j+7] = static_cast<uint8_t>(right >> 24u);
50 }
51}
52
53}
54
55void encrypt(uint8_t* data, size_t length, const key& k)
56{
57 for (uint32_t i = 0, sum = 0, next_sum = sum + delta; i < 32; ++i, sum = next_sum, next_sum += delta) {
58 apply_rounds(data, length, [&](uint32_t& left, uint32_t& right) {
59 left += ((right << 4 ^ right >> 5) + right) ^ (sum + k[sum & 3]);
60 right += ((left << 4 ^ left >> 5) + left) ^ (next_sum + k[(next_sum >> 11) & 3]);
61 });
62 };
63}
64
65void decrypt(uint8_t* data, size_t length, const key& k)
66{
67 for (uint32_t i = 0, sum = delta << 5, next_sum = sum - delta; i < 32; ++i, sum = next_sum, next_sum -= delta) {
68 apply_rounds(data, length, [&](uint32_t& left, uint32_t& right) {
69 right -= ((left << 4 ^ left >> 5) + left) ^ (sum + k[(sum >> 11) & 3]);
70 left -= ((right << 4 ^ right >> 5) + right) ^ (next_sum + k[next_sum & 3]);
71 });
72 };
73}
74
75} // namespace xtea
76
Top