Zero_Digits
Zero_Digits

Reputation: 23

Password decryption using XOR algorithm in C#. Program doesn't work for unknown reason

The function is that it takes a given password, and a key to reveal the password with. After that it uses XOR algorithm to decrypt the password into a cypher. The cypher is at last printed out to the user.

But it prints out nothing. I have found that if i input digits instead of letters in either password or key it prints out all the chars in their int representations

Console.Write("INPOUT YOUR PASSWORD: ");
string password = Console.ReadLine();

Console.WriteLine("INPUT YOUR KEY TO HIDE YOUR PASSWORD WITH: ");
string key = Console.ReadLine();

char[] passwordChar = password.ToCharArray();
char[] keyChar = key.ToCharArray();
int countForKey = 0;

StringBuilder cypher = new StringBuilder(passwordChar.Length);

for(int i = 0; i < passwordChar.Length; i++)
{
    char temp = (char)(passwordChar[i] ^ keyChar[countForKey]); //Doesnt work

    cypher.Append(temp);

    countForKey++;

    if(countForKey == key.Length)
    {
        countForKey = 0;
    }
}

Console.WriteLine("The password cypher is: {0}", cypher);

Upvotes: 1

Views: 431

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109657

The reason you're getting unexpected output is because when you XOR some characters, the result will not be printable.

For example, consider XORing 'W' and 'A':

  Char code
W 0101-0111
A 0100-0001
  ---------
  0001-0110

The resultant char code, 00010110, is "SYN" (Synchronous Idle), which is NOT a printable character, and will result in either a blank or a box character output (not sure which).

Another example:

  Char code
X 0101 1000
a 0110 0001
  ---------
9 0011 1001

In this case, XORing X and a results in 9.

Upvotes: 2

Related Questions