| 40 | /// \tparam N The number of bytes of the string (including the null terminal byte). |
| 41 | template<std::size_t N> |
| 42 | struct ObfuscatedString { |
| 43 | /// Construct an obfuscated string of characters. |
| 44 | /// \param str The array of characters (including the null terminal byte). |
| 45 | consteval ObfuscatedString(char const (&str)[N]) noexcept |
| 46 | : algos_{generate_sum(str)} { |
| 47 | encode(str); |
| 48 | }; |
| 49 | |
| 50 | /// Construct an obfuscated string of characters. |
| 51 | /// \param str The array of characters (including the null terminal byte). |
| 52 | /// \param params The parameters for the obfuscation (key and algorithms). |
| 53 | consteval ObfuscatedString(char const (&str)[N], const Parameters ¶ms) noexcept |
| 54 | : algos_{params} { |
| 55 | encode(str); |
| 56 | } |
| 57 | |
| 58 | /// Construct an obfuscated string of characters. |
| 59 | /// \param str The array of characters (including the null terminal byte). |
| 60 | /// \param params An array of parameters for the obfuscations (keys and algorithms). |
| 61 | template<std::size_t A> |
| 62 | consteval ObfuscatedString(char const (&str)[N], const Parameters (¶ms)[A]) noexcept |
| 63 | : algos_{params} { |
| 64 | static_assert(A <= details::MAX_NB_ALGORITHMS, "Maximum number of parameters overflow"); |
| 65 | encode(str); |
| 66 | } |
| 67 | |
| 68 | /// Destruct an obfuscated string by first erasing its content. |
| 69 | constexpr ~ObfuscatedString() noexcept { erase(); } |
| 70 | |
| 71 | /// Implicit conversion to a pointer to (const) characters, like a regular string. |
| 72 | operator const char* () noexcept { |
| 73 | constexpr auto random = call::generate_random(__LINE__); |
| 74 | const ObfuscatedMethodCall call{random, &ObfuscatedString::decode_inplace}; |
| 75 | call(random, this); |
| 76 | return data_.data(); |
| 77 | } |
| 78 | |
| 79 | /// Get the raw (encrypted) content. |
| 80 | [[nodiscard]] const char *raw() const noexcept { return data_.data(); } |
| 81 | |
| 82 | /// Get the actual length of the string. |
| 83 | [[nodiscard]] constexpr std::size_t size() noexcept { return N - 1; } |
| 84 | |
| 85 | /// Decode the obfuscated string |
| 86 | [[nodiscard]] constexpr std::string decode() const { |
| 87 | std::array<std::uint8_t, N> buffer; |
| 88 | std::copy(data_.begin(), data_.end(), buffer.begin()); |
| 89 | if(obfuscated_) algos_.decode(0, buffer.begin(), buffer.end()); |
| 90 | std::string str; |
| 91 | str.resize(N - 1); |
| 92 | std::copy(buffer.begin(), buffer.end() - 1, str.begin()); |
| 93 | return str; |
| 94 | } |
| 95 | |
| 96 | /// Encoded or decoded data. |
| 97 | std::array<char, N> data_{}; |
| 98 | /// Obfuscations used to encode the data. |
| 99 | Obfuscations algos_; |