Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Last active November 17, 2017 01:39
Show Gist options
  • Save JKamsker/a8f33c5f21043f251067f5dcb562a397 to your computer and use it in GitHub Desktop.
Save JKamsker/a8f33c5f21043f251067f5dcb562a397 to your computer and use it in GitHub Desktop.
Lighning fast xor crypt
using System.Runtime.CompilerServices;
namespace TestingEnv
{
internal class XoRCrypto
{
private readonly int[] _keyChain;
private int _ckey;
public XoRCrypto(int[] chain = null)
{
_ckey = 0;
_keyChain = chain ?? new[]
{
1234,
2341,
3412,
4123,
5555,
3214,
5656,
1337
};
}
public unsafe void Encrypt(byte[] buffer, int length = -1)
{
var iterations = 0;
if (length == -1 || length > buffer.Length)
length = buffer.Length / sizeof(int);
else
length = length / sizeof(int);
var ikey = _keyChain[_ckey];
fixed (byte* pBuf = buffer)
{
var asint = (int*)pBuf;
for (var i = 0; i < length; i++)
{
*asint ^= ikey + i;
asint++;
if (*asint % 100 == 0)
{
MoveNext();
ikey = _keyChain[_ckey];
iterations++;
}
}
}
MoveNext();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void MoveNext()
{
var cKey = _ckey;
var cLen = _keyChain.Length;
fixed (int* pInt = _keyChain)
{
var keyVal = pInt[cKey]; //*(pInt + cKey);
for (var i = 0; i < cLen; i++)
{
if (i == cKey)
continue;
pInt[i] += keyVal;
// *(pInt + i) += keyVal;
}
}
if (cKey == cLen - 1)
cKey = 0;
else
cKey++;
_ckey = cKey;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment