68 lines
1.5 KiB
C++
68 lines
1.5 KiB
C++
#pragma once
|
|
|
|
#include "types.h"
|
|
#include <cstdint>
|
|
#include <vector>
|
|
#include <array>
|
|
#include <span>
|
|
|
|
namespace metin2::network {
|
|
|
|
using TeaKey = std::array<uint32_t, 4>;
|
|
|
|
class TeaCipher {
|
|
public:
|
|
TeaCipher() = default;
|
|
explicit TeaCipher(const TeaKey& key);
|
|
|
|
void SetKey(const TeaKey& key);
|
|
const TeaKey& GetKey() const { return m_key; }
|
|
|
|
void EncryptBlock(uint32_t& y, uint32_t& z) const;
|
|
void DecryptBlock(uint32_t& y, uint32_t& z) const;
|
|
|
|
std::vector<uint8_t> Encrypt(std::span<const uint8_t> input) const;
|
|
std::vector<uint8_t> Decrypt(std::span<const uint8_t> input) const;
|
|
|
|
private:
|
|
TeaKey m_key{0, 0, 0, 0};
|
|
};
|
|
|
|
class RollingXorCipher {
|
|
public:
|
|
RollingXorCipher() = default;
|
|
explicit RollingXorCipher(uint32_t seed_key);
|
|
|
|
void Reset(uint32_t seed_key);
|
|
void Process(uint8_t* data, size_t size);
|
|
|
|
private:
|
|
uint32_t m_key = 0;
|
|
uint32_t m_state = 0;
|
|
};
|
|
|
|
class CipherContext {
|
|
public:
|
|
CipherContext() = default;
|
|
|
|
void SetEnabled(bool enabled) { m_enabled = enabled; }
|
|
bool IsEnabled() const { return m_enabled; }
|
|
|
|
void InitializeKeys(const TeaKey& tea_key, uint32_t xor_seed);
|
|
|
|
void EncryptSend(uint8_t* data, size_t size);
|
|
void DecryptRecv(uint8_t* data, size_t size);
|
|
|
|
TeaCipher& GetSendTea() { return m_send_tea; }
|
|
TeaCipher& GetRecvTea() { return m_recv_tea; }
|
|
|
|
private:
|
|
bool m_enabled = false;
|
|
TeaCipher m_send_tea;
|
|
TeaCipher m_recv_tea;
|
|
RollingXorCipher m_send_xor;
|
|
RollingXorCipher m_recv_xor;
|
|
};
|
|
|
|
} // namespace metin2::network
|