Search code examples
c#encryptionxor

Are there any rules for the XOR cipher?


I have the following method which takes the plain text and the key text. It is supposed to return a string encrypted with the XOR method as ascii.

public static string encryptXOREng(string plainText,string keyText) 
        {
            StringBuilder chiffreText = new StringBuilder();

            byte[] binaryPlainText = System.Text.Encoding.ASCII.GetBytes(plainText);

            byte[] binaryKeyText = System.Text.Encoding.ASCII.GetBytes(keyText);


            for(int i = 0;i<plainText.Length;i++)
            {
                int result = binaryPlainText[i] ^ binaryKeyText[i];
                chiffreText.Append(Convert.ToChar(result));
            }

            return chiffreText.ToString();
        }

For some characters it runs just fine. But for example if it performs XOR on 'G' & 'M', which is 71 XOR 77 it returns 10. And 10 stands for Line feed. This is then actually not represented by a character in my output. This leads to a plain text of a length being encrypted to a cipher string which is only 2 characters long, in some cases. I suppose this would make a decryption impossible, even with a key? Or are the ascii characters 0 - 31 there but simply not visible?


Solution

  • To avoid non printable chars use Convert.ToBase64String

    public static string encryptXOREng(string plainText, string keyText)
    {
        List<byte> chiffreText = new List<byte>();    
    
        byte[] binaryPlainText = System.Text.Encoding.ASCII.GetBytes(plainText);
    
        byte[] binaryKeyText = System.Text.Encoding.ASCII.GetBytes(keyText);
    
    
        for (int i = 0; i < plainText.Length; i++)
        {
            int result = binaryPlainText[i] ^ binaryKeyText[i % binaryKeyText.Length];
            chiffreText.Add((byte)result);
        }
    
        return Convert.ToBase64String(chiffreText.ToArray());
    }
    

    PS: In your code you assume keyText is not shorter than plainText, I fixed it also.