views:

268

answers:

5

Might a base64 encoded string contain whitespace? Specifically, could it contain whitespace at the end of the string?

PS. I'm thinking about the whole "MySQL will trim trailing whitespace when storing strings in VARCHAR fields" here ;-)

A: 

Yes we can

I mean it can

Redlab
+1  A: 

No it can't. See Base64 for the allowed character repository used by base64, which are the characters A-Z, a-z, 0-9, + and / (the last two may differ depending on the implementation) as well as the padding character = (but that's also implementation dependent as some implementations don't use padding at all).

Stefan Gehrig
yes it can, they don't belong to the code, but in most implementations they can added to maintain readability. Most decoders ignore whitespaces.
jigfox
Yes that's true but then they are not significant to the encoded string which means that they can safely be ignored and it doesn't matter if MySQL or whoever will strip them away. The OP's intention is obviously to store `base64`-encoded strings in a MySQL `VARCHAR` column which is absolutely save.
Stefan Gehrig
THanks guys, I meant more "does" a base64 string contain spaces - not "can" - my fault. So in conclusion it CAN but they are irrelevant. :-) I get it now
Dougal
A: 

Wikipedia suggests that there're like a gazillion variations of the Base64 encoding:

http://en.wikipedia.org/wiki/Base64

So the answer probably depends on what you need to do with the string. But I'd dare say you created in PHP with base64_encode() so it appears to be safe to append blanks:

<?php

$original_data = 'Lorem ipsum dolor sit amet';
$encoded_data = base64_encode($original_data);
$padded_data = '    ' . chunk_split($encoded_data, 3, '  ') . '    ';

echo base64_decode($padded_data); // Prints 'Lorem ipsum dolor sit amet'

?>
Álvaro G. Vicario
A roundabout way of proving it I suppose! Thanks
Dougal
A: 

As far as I know it cannot. Basically a Base64 string must be constructed from a set of 64 characters. A-Z, a-z, 0-9 make 62 - the other two depend on the implementation.

Based on what I know, there is now implementation that will use white space as a character. Main reason for that is readability - i.e. a Base64 string must be easily printed and recognized.

You'd probably find more info about it on Wikipedia.

Ivan Zlatanov
Useful and interesting. Thanks
Dougal
+1  A: 

Yes. Base64-encoded string can contain white-spaces but the characters are not significant. So it's ok if database trims spaces.

As a matter of fact, the original MIME specification recommends to break Base64 strings into lines of 72 characters. base64Binary of XML may also include newlines, tabs, spaces.

In PHP, base64_decode() strips all whiltespace characters so you don't have to worry about it.

ZZ Coder