Search code examples
c#algorithmxorunsafecrypt

Fast XOR Algorithm


Is there a way to improve the speed for a XOR-Encryption Algorithm somehow by using some tricks (unsafe code or so)?

My current algorithm I am using is the following:

public byte[] XOR(byte[] strng, byte[] key)
{
    int string_len = strng.Length;
    int key_length = key.Length;
    int i, position;

    for (i = 0; i < string_len; i++)
    {
        position = i % key_length;
        strng[i] = Convert.ToByte(strng[i] ^ key[position]);
    }
    return strng;
}

Can this function be improved and speed up somehow?


Solution

  • If and only if both arrays are aligned the same, you can go quite a lot faster by using a 64-bit XOR instead of an 8-bit XOR.

    Even absent alignment, unrolling the loop will reduce the overhead from the loop termination condition and branching.

    And definitely get rid of the % operator. Since you only move forward one element at a time, wrapping around can be implemented by a single subtraction.

    Normally the optimizing compiler is supposed to do these sorts of things for you, but the JIT might not be as smart about optimization as, for example, a mature C++ optimizer.