Chieko
Chieko

Reputation: 11

XOR String Decryption give me as output below 0 Error. How can I bypass it?

I am currently trying to encrypt strings that can be decrypted. Since I am just starting with this topic I have a problem which arises from the calculation of the XOR and I would like to know if there is a way around this or if there is another type of encryption where this does not occur.

My problem is that I want to encrypt a string that is 30 characters long but the password is only 15 characters. Since you can't divide below 0 to decrypt the string there is no way to undo it.

Is there another type of encryption and decryption that does not have this problem? Or can you trick the XOR so that it works anyway? Would be nice if someone could help me :)

My Code:

To Encrypt String:

 public static string XOREncrypt(string text, string password)
    {
        string strKey = password;
        string strIn = text;
        string sbOut = String.Empty;
        for (int i = 0; i < strIn.Length; i++)
        {
            sbOut += String.Format("{0:00}", strIn[i] ^ strKey[i % strKey.Length]);
        }

        return sbOut;
    }

To Decrypt

 public static string XORDecrypt(string text, string password)
    {
        string strKey = password;
        string strIn = text;
        string sbOut = String.Empty;
        for (int i = 0; i < strIn.Length; i += 2)
        {
            byte code = Convert.ToByte(strIn.Substring(i, 2));
            sbOut += (char)(code ^ strKey[(i / 2) % strKey.Length]);
        }

        return sbOut;
    }

Upvotes: 0

Views: 170

Answers (1)

JonasH
JonasH

Reputation: 36531

You should convert your strings to bytes first and do the XOR on the individual bytes.

byte[] bytes = Encoding.UFT8.GetBytes(text);

And to convert back again

string text = Encoding.UTF8.GetString(bytes);

Upvotes: 1

Related Questions