Skip to content

Instantly share code, notes, and snippets.

@i-e-b
Created October 4, 2022 11:36
Show Gist options
  • Save i-e-b/a66f5890cabbc7f69e6c39e8f60bf9b4 to your computer and use it in GitHub Desktop.
Save i-e-b/a66f5890cabbc7f69e6c39e8f60bf9b4 to your computer and use it in GitHub Desktop.
Tiny crypto (C# version of https://jsfiddle.net/i_e_b/4rqo268h/)
[Test]
public void tiny_crypto()
{
var key = new byte[] { 55, 167, 44, 86, 217 };
var secretMessage = "This is the input text";
var input = Encoding.UTF8.GetBytes(secretMessage);
var encrypted = Encode(input, key);
var result = Decode(encrypted, key);
var recovered = Encoding.UTF8.GetString(result);
Assert.That(recovered, Is.EqualTo(secretMessage));
}
private static Random rnd = new();
public static byte[] Encode(byte[] input, byte[] key)
{
const int mod = 251;
var result = new byte[input.Length + 1];
var keyL = key.Length;
var s = rnd.Next(0, 255);
result[0] = (byte)(s ^ key[0]);
for (int i = 0; i < input.Length; i++)
{
s = (s * (i + 1)) % mod;
var code = s ^ key[i % keyL] ^ input[i];
result[i + 1] = (byte)code;
}
return result;
}
public static byte[] Decode(byte[] input, byte[] key)
{
const int mod = 251;
var keyL = key.Length;
var result = new byte[input.Length - 1];
var s = input[0] ^ key[0];
for (int i = 0; i < result.Length; i++)
{
s = (s * (i + 1)) % mod;
var decode = s ^ key[i%keyL] ^ input[i+1];
result[i] = (byte)decode;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment