XOR-ing strings in C#

user1213042 picture user1213042 · Feb 20, 2013 · Viewed 28.8k times · Source

I recently started playing around with C#, and I'm trying to understand why the following code doesn't compile. On the line with the error comment, I get:

Cannot implicitly convert type 'int' to 'char'. An explicit conversion exits (are you missing a cast?)

I'm trying to do a simple XOR operation with two strings.

public string calcXor (string a, string b)
{
    char[] charAArray = a.ToCharArray();
    char[] charBArray = b.ToCharArray();
    char[] result = new char[6];
    int len = 0;

    // Set length to be the length of the shorter string
    if (a.Length > b.Length)
        len = b.Length - 1;
    else
        len = a.Length - 1;

    for (int i = 0; i < len; i++) {
        result[i] = charAArray[i] ^ charBArray[i]; // Error here
    }

    return new string (result);
}

Answer

Ton Snoei picture Ton Snoei · Oct 10, 2013

If you use XOR-ing to hide data, take a look at the code below. The key will be repeated as long as necessary. It is maybe a shorter/better approach:

public static string xorIt(string key, string input)
{
    StringBuilder sb = new StringBuilder();
    for(int i=0; i < input.Length; i++)
        sb.Append((char)(input[i] ^ key[(i % key.Length)]));
    String result = sb.ToString ();

    return result;
}