0

I have the following C++ code to cipher a string with XOR.

#define MPI_CIPHER_KEY "qwerty"

Buffer FooClient::cipher_string(const Buffer& _landing_url)
{
    String key(CIPHER_KEY);
    Buffer key_buf(key.chars(), key.length());
    Buffer landing_url_cipher = FooClient::XOR(_url, key_buf);

    Buffer b64_url_cipher;
    base64_encode(landing_url_cipher, b64_url_cipher);

    return b64_url_cipher;
}

Buffer FooClient::XOR(const Buffer& _data, const Buffer& _key)
{
    Buffer retval(_data);
    unsigned int klen=_key.length();
    unsigned int dlen=_data.length();
    unsigned int k=0;
    unsigned int d=0;

    for(;d<dlen;d++)
    {
        retval[d]=_data[d]^_key[k];
        k=(++k<klen?k:0);
    }

    return retval;
}

I have seen in this question such java impl. would that work for this case?

String s1, s2;

StringBuilder sb = new StringBuilder();
for(int i=0; i<s1.length() && i<s2.length();i++)
    sb.append((char)(s1.charAt(i) ^ s2.charAt(i)));
String result = sb.toString();

or is there an easier way to do it?

Community
  • 1
  • 1
DarthVader
  • 52,984
  • 76
  • 209
  • 300

2 Answers2

3

doesn't look the same to me. the c++ version loops across all of _data no matter what the _key length was, cycling through _key as necessary. (k=(++k<klen?k:0); in the c++ code)

yours returns as soon as the shortest of key or data is hit.

Personally, i'd start with the closest literal translation of C++ to java that you can do, keeping param and local names the same.

Then write unit tests for it that have known inputs and outputs from C++

then start refactoring the java version into using java idioms/etc ensuring the tests still pass.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
1

No - the java code will only XOR up to the length of the smaller string - whereas the C++ code will XOR the entire data completely. Assuming s1 is your "key" this can be fixed by changing to

for(int i=0; i<s2.length();i++)
     sb.append((char)(s1.charAt(i%s1.length()) ^ s2.charAt(i)));

Also the base-64 encoding of the return value is missing.

kjp
  • 3,086
  • 22
  • 30