0

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?

Dmitry
  • 13,797
  • 6
  • 32
  • 48
yq8
  • 145
  • 1
  • 10
  • I would recommend detailing why you want it to go faster, speed for the sake of speed is typically frown upon, as we don't have enough information to know whether the trade-offs are worth it without understanding your need. – Guvante Apr 16 '15 at 21:46
  • http://c2.com/cgi/wiki?PrematureOptimization – EZI Apr 16 '15 at 21:48
  • 1
    You could slightly simplify the code using `strng[i] ^= key[position];` – Dmitry Apr 16 '15 at 21:49
  • Why do we always have to assume all optimization is premature? Can't we give OP the benefit of the doubt? This does look like a method that *could* be a performance problem. By the way you can get rid of that "modulo by a non-constant". – harold Apr 16 '15 at 21:53
  • Might I ask why my question directly gets downvoted? – yq8 Apr 16 '15 at 21:57
  • I just like to get some advice or ideas for improvement, and just downvoting won't help me here, furthermore this downvote doesn't seem justified to me either. – yq8 Apr 16 '15 at 21:58
  • @harold: Sorry if my wording was vague, it is a complicated topic. I was trying to say "people think about premature optimization if you don't justify" and detailing *why* you need performance is helpful, even if it is "this other program did it faster" you provide a more complete question to answer. – Guvante Apr 16 '15 at 22:00

1 Answers1

1

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720