Created
September 17, 2023 18:39
-
-
Save alza54/3bd75329b491f60e299f9a0ca2fc6b75 to your computer and use it in GitHub Desktop.
C++: Automatic String XOR in compile-time with unique seeds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <string> | |
namespace os2 { | |
namespace string { | |
constexpr uint32_t modulus() { return 0x7fffffff; } | |
// Create entropy using __FILE__ and __LINE__ | |
template <size_t N> | |
constexpr uint32_t seed(const char (&entropy)[N], const uint32_t iv = 0) { | |
auto value{iv}; | |
for (size_t i{0}; i < N; i++) { | |
// Xor 1st byte of seed with input byte | |
value = (value & ((~0) << 8)) | ((value & 0xFF) ^ entropy[i]); | |
// Rotl 1 byte | |
value = value << 8 | value >> ((sizeof(value) * 8) - 8); | |
} | |
// The seed is required to be less than the modulus and odd | |
while (value > modulus()) value = value >> 1; | |
return value << 1 | 1; | |
} | |
constexpr uint32_t prng(const uint32_t input) { | |
return (input * 48271) % modulus(); | |
} | |
} // namespace string | |
}; // namespace os2 | |
template <typename T, size_t N> | |
struct encrypted { | |
int seed; | |
T data[N]; | |
}; | |
template <size_t N> | |
constexpr auto crypt(const char (&input)[N], const uint32_t seed = 0) { | |
encrypted<char, N> blob{}; | |
blob.seed = seed; | |
for (uint32_t index{0}, stream{seed}; index < N; index++) { | |
blob.data[index] = input[index] ^ stream; | |
stream = os2::string::prng(stream); | |
} | |
return blob; | |
} | |
#define os2_string(STRING) \ | |
([&] { \ | |
constexpr auto _{crypt(STRING, os2::string::seed(__FILE__, __LINE__))}; \ | |
return std::string{crypt(_.data, _.seed).data}; \ | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment