/*! * \brief * * \copyright Copyright (c) 2023 Diality Inc. - All Rights Reserved. * * \file Obfuscate.cpp * * \author PBraica * \date March 2023 */ #include "Obfuscate.h" #include /* time to seed secret. */ #define HEADER_SIZE (2) #define COPRIME_1 (19) #define COPRIME_2 (23) #define ROT_VAL (211) // Change to 211. /*! * \brief Constructor. */ Obfuscate::Obfuscate() { _secret = (unsigned char)time(NULL) % 0xFF; } /*! * \brief Virtual destructor. */ Obfuscate::~Obfuscate() { ; // NOP. } /*! * \brief Encode the bytes in data. * * \param data The data to encode. * * \return Encoded bytes in a string, unlikely printable. */ std::string Obfuscate::encode(const std::string& data) { unsigned char s = _secret; std::string rv = std::string(data.size() + HEADER_SIZE, ' '); std::size_t ii = 0; rv[ii++] = s % COPRIME_1; rv[ii++] = s % COPRIME_2; for (char c : data) { rv[ii++] = (c + s) % 256; s += ROT_VAL; } return rv; } /*! * \brief Decode the bytes in data. * * \param data The string to decode. * \param is_start True if we need to recover the secret. * * \return Decoded bytes in a string, printable if the original was. */ std::string Obfuscate::decode(const std::string & data, bool is_start) { return decode(&data[0], data.size(), is_start); } /*! * \brief Decode the bytes in pdata. * * \return Decoded bytes in a string, printable if the original was. */ std::string Obfuscate::decode(const char* pData, std::size_t size_bytes, bool is_start) { std::string rv; std::size_t headerSize = (is_start ? HEADER_SIZE : 0); if (size_bytes <= headerSize) { // Either really no data OR not enough input data. return rv; } bool found = false; int s = 0; if (is_start) { // static int decoder[ROT_VAL / COPRIME_1]; unsigned int a = (unsigned int)pData[0]; unsigned int b = (unsigned int)pData[1]; unsigned short code = (a << 8) + b; for (s = 0; s < 0xFF; s++) { unsigned short test = ((s % COPRIME_1) << 8) + (s % COPRIME_2); if (code == test) { _secret = s; found = true; break; } } } if (!found) { // Given an invalid code pair. return rv; } rv.resize(size_bytes - headerSize, ' '); for (std::size_t ii = headerSize; ii < size_bytes; ii++) { char d = pData[ii]; rv[ii - headerSize] = (d - s) % 256; s += ROT_VAL; } _secret = s % 256; return rv; } /*! * \brief Get the header size. * * \return Header size in bytes. */ std::size_t Obfuscate::headerSize() { return HEADER_SIZE; }