Cross platform string XOR with juce?


#1

Hello all,

A while ago I wrote a simple string XOR in juce which works fine on windows. Today I tried it out on OSX and my unit test totally fails… I was wondering if there is any cross-platform way to go back and forth from a string to something that can be easily xor’d. This is what I wrote (which is probably completely naive??). I suppose I will run into trouble because of differently encoded strings on different platforms? My “key” is always in the ascii range, but the input might not be (i.e. it might contain special chars). Any hints would be appreciated…

    String DoXOR(const String& input, const String& key, bool encode)
    {
        if (key.isEmpty())
            return input;

        if (encode)
        {
            String::CharPointerType charPointer1 = input.getCharPointer();
            String::CharPointerType charPointer2 = key.getCharPointer();
            
            std::vector<juce_wchar> encoded;
            encoded.reserve(input.length() + 1);

            while (!charPointer1.isEmpty())
            {
                juce_wchar char1 = charPointer1.getAndAdvance();
                juce_wchar char2 = charPointer2.getAndAdvance();

                encoded.push_back(char1 ^ char2);

                if (charPointer2.isEmpty())
                    charPointer2 = key.getCharPointer();
            }

            MemoryBlock mb;
            mb.setSize(sizeof(juce_wchar)*encoded.size());
            mb.copyFrom(&encoded[0], 0, sizeof(juce_wchar)*encoded.size());

            return mb.toBase64Encoding();
        }
        else
        {
            MemoryBlock mb;
            mb.fromBase64Encoding(input);

            std::vector<juce_wchar> encoded;
            encoded.resize(mb.getSize() / sizeof(juce_wchar), 0);
            mb.copyTo(&encoded[0], 0, mb.getSize());

            String::CharPointerType charPointer2 = key.getCharPointer();

            String output = "";

            for (unsigned long i=0; i<encoded.size(); i++)
            {
                juce_wchar char2 = charPointer2.getAndAdvance();

                output += encoded[i] ^ char2;

                if (charPointer2.isEmpty())
                    charPointer2 = key.getCharPointer();
            }

            return output;
        }
    }

#2

Hah, looks like it was a rather simple fix:

output += encoded[i] ^ char2;

needs to be

output += juce_wchar(encoded[i] ^ char2);

testing with some UTF8 strings now to see if that works…

  • bram