C#中使用异或算法解密密码。程序因未知原因无法运行

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

功能是它接受一个给定的密码,以及一个用来揭示密码的密钥。之后它使用异或算法将密码解密成密码。密码最终打印出来给用户。

但它什么也没打印出来。我发现如果我在密码或密钥中输入数字而不是字母,它会打印出其 int 表示中的所有字符

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);

您得到意外输出的原因是当您对某些字符进行异或时,结果将无法打印。

例如,考虑 XORing 'W' 和 'A':

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

生成的字符代码 00010110 是 "SYN"(同步空闲),它不是可打印字符,将导致空白字符或框字符输出(不确定是哪个)。

另一个例子:

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

在这种情况下,Xa 的异或结果为 9