0

I'm trying out xor encryption for strings in Python but for some reason I'm getting this weird output in terminal. Although the decryption runs just fine, transferring this data seems to be causing an error.

Line 1 is the plaintext string, 2-3 are the encrypted string output, 4 is the encrypted string decrypted, and 5 is the byte string for the encrypted string.

Hello world!
<
    U
Hello world!
\x3c\x0\x1f\x18\x1b\x45\x4\x1b\x6\x9\x17\x55

Here's how the encryption is working in Python.

    def encrypt(self, plaintext: str) -> str:
        ciphertext = ""

        for i in range(len(plaintext)):
            current = plaintext[i]
            current_key = self.key[i%len(self.key)]
            ciphertext += chr(ord(current) ^ ord(current_key))

        return ciphertext

And to actually call the encryption method is as follows.

            tmp2 = tmp2.strip('"')
            encryption = Encryption(self.key)
            encrypted_string = encryption.encrypt(tmp2)
            byte_string = encryption.to_byte_string(
                encrypted_string.encode('utf-8'))

What I'm trying to do with the last line of output (byte string), is decrypt this xor string in a C++ program. However the output for that program is just giving me an H.

#define POLY_ENGINE_KEY "test"

static string Decrypt(string ciphertext)
    {
        string plaintext = ciphertext;

        for (int i = 0; i < ciphertext.size(); i++)
            plaintext[i] = ciphertext[i] ^ POLY_ENGINE_KEY[i % (sizeof(POLY_ENGINE_KEY) / sizeof(char))];

        return plaintext;
    }

Greatly appreciate some help with this.

0

1 Answer 1

0

Most likely the length/size of ciphertext is 1 in Decrypt(). It maybe because that encrypted text contains 0x00(NULL) ascii value in second place. So, turning that character array into std::string (I am guessing that what you have done in your code) makes a string with only one character. String constructor that takes only character array expects that the character array is NULL terminated. So, as it encounters NULL in second position, it creates a string with only the first character.You can try to create the string mentioning the length of the array alongside the character array. Like these -

char ciphered_bytes[] = {....};
int size = sizeof(ciphered_bytes)/sizeof(ciphered_bytes[0]);
std::string ciphertext(ciphered_bytes, size); // instead of only ciphertext(ciphered_bytes)

// Then call the Decrypt
std::string plaintext = Decrypt(ciphertext);

Also you might want to change string of Decrypt() to const string& as you are not changing the input string ciphertext.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.