mattbee
mattbee

Reputation: 592

Decoding AES Strings containing spaces

In receiving a URL from an iPhone app, we are decrypting a string created in Objective-C and passed to our PHP website as a GET variable.

We are decoding using:

mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $padded_key, base64_decode($base64encoded_ciphertext), 'ecb');

Which is working fine the majority of the time But sometimes, we receive a string containing a space, for example:

mypage.php?score=IEZrdQ5iUECe9 xyfTY5Cg==

Then the decryption fails and we are left with a result like this:

the result http://mattbee.co.uk/temp/mess.png

Has anyone any idea how to handle strings with spaces in the middle of them, should spaces even exist? I would have thought encoding might have something to do with it but converting to UTF-8/UTF-16 didn't help.

Any advice greatly appreciated.

Upvotes: 0

Views: 2219

Answers (3)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74810

Base64 can represent arbitrary bytes, which is just what is necessary for ciphertext. Do not recode to anything else.

Some software inserts spaces and line-breaks in base64-encoded strings, so they fit into emails and other line-length limited formats. These should be ignored or removed when decoding.

If there are spaces inside the base64-encoded string, you could strip them out before decoding, though I think that base64_decode should do this automatically.

Another note: Do not use ECB-mode, it is insecure. Use CBC-mode (with a random initialization vector sent with the message). Or even better, don't encrypt parts of a URL, use SSL (or TLS) instead, which will handle all the details for you.

Upvotes: 2

Jason Foglia
Jason Foglia

Reputation: 2551

You could go with bin2hex then use pack('H*', hex) to decode the string. The only issue I know with this method is that the string can grow very big.

Upvotes: 0

thatwasbrilliant
thatwasbrilliant

Reputation: 521

Base64 data contains whitespace every 64 characters, and 0-2 equal signs at the end. So the iPhone app should percent-encode it before sending as a GET variable.

Upvotes: 2

Related Questions