Search code examples
c#textxor

TextBox text and xor filter


my problem today in C#. I make xor crypt for my text lines, and want make for it generator, but my TextBox with source text return diffential string and result is not true.

Xor function:

private string GetText(byte[] Text)
{
    byte[] Key = { 0x12, 0x05, 0x52 };
    // ----
    for (int i = 0; i < Text.Length; i++)
    {
        Text[i] ^= Key[i % 3];
    }
    // ----
    return Encoding.ASCII.GetString(Text);
}

True result:

string Text = ".\\MyExample.txt";
textBox2.Text = GetText(Encoding.ASCII.GetBytes(Text)); //Result: <Yk@*sh"~`|f}&

False result:

string Text = textBox1.Text; //Text: ".\\MyExample.txt"
textBox2.Text = GetText(Encoding.ASCII.GetBytes(Text)); //Result: <Y_|jd?bi7<q*f

Why i get different results and how it fix?


Solution

  • Your code contains an escaped backslash. C# is converting \\ to a single \:

    string Text = ".\\MyExample.txt";  // Text == ".\MyExample.txt"
    

    If you want Text to contain \\, use one of the following methods:

    string Text = @".\\MyExample.txt";
    string Text = ".\\\\MyExample.txt";