简体   繁体   中英

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?

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.

As far as i know there are no rules specific to xor-ciphers. Cryptographic functions often output values that are not printable, which makes sense - the result is not supposed to be readable. In stead you may want to use the output bytes directly or a base64 encoded result.

I would do something like:

public static byte[] XORCipher(string plainText, string keyText)
{
    byte[] binaryPlainText = System.Text.Encoding.ASCII.GetBytes(plainText);
    byte[] binaryKeyText = System.Text.Encoding.ASCII.GetBytes(keyText);

    for(int i = 0;i<plainText.Length;i++)
    {
        binaryPlainText[i] ^= binaryKeyText[i];
    }
    return binaryPlainText;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM