Skip to content

Instantly share code, notes, and snippets.

@Kittoes0124
Created October 2, 2023 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kittoes0124/01e8306ae32a427f9edab1bbe2303ad6 to your computer and use it in GitHub Desktop.
Save Kittoes0124/01e8306ae32a427f9edab1bbe2303ad6 to your computer and use it in GitHub Desktop.
This silly implementation of an encryption algorithm uses a [Cunningham chain](https://en.wikipedia.org/wiki/Cunningham_chain) to obscure a 32-bit value.
public class StupidEncryption
{
private const string STREAM_VALUE_ERROR = "Stream offset must be a positive integer less than 2^31.";
private const uint STREAM_VALUE_MAX = ((1U << 31) - 1U);
public static uint Seed = 4125763933U;
public static uint PrimeModularInverse1 = (Seed - 2U); // 4125763931
public static uint Prime1 = PrimeModularInverse1.ModularInverse(); // 0920248019
public static uint Prime0 = (Prime1 >> 1); // 0460124009
public static uint Prime2 = ((Prime1 << 1) | 1U); // 1840496039
public static uint Prime3 = ((Prime1 << 2) | 3U); // 3680992079
public static uint PrimeModularInverse0 = Prime0.ModularInverse(); // 1213108441
public static uint PrimeModularInverse2 = Prime2.ModularInverse(); // 3364952599
public static uint PrimeModularInverse3 = Prime3.ModularInverse(); // 3016801199
private static uint Decode(uint stream, uint value) =>
(((value * PrimeModularInverse1 * PrimeModularInverse2 * Prime0 * Prime3) - stream) ^ Seed);
private static uint Encode(uint stream, uint value) =>
(((value ^ Seed) + stream) * Prime1 * Prime2 * PrimeModularInverse0 * PrimeModularInverse3);
private readonly uint m_stream;
public StupidEncryption(uint stream) {
if (stream > STREAM_VALUE_MAX) {
throw new ArgumentOutOfRangeException(actualValue: stream, message: STREAM_VALUE_ERROR, paramName: nameof(stream));
}
m_stream = ((((~(stream & 1U)) << 31) | stream) | 1U);
}
public uint Decode(uint value) =>
Decode(stream: m_stream, value: value);
public uint Encode(uint value) =>
Encode(stream: m_stream, value: value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment