Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is base64_encode() adding a slash "/" in the result?

I am encoding the URL suffix of my application:

$url = 'subjects?_d=1'; echo base64_encode($url);  // Outputs c3ViamVjdHM/X2Q9MQ== 

Notice the slash before 'X2'.

Why is this happening? I thought base64 only outputted A-Z, 0-9 and '=' as padding?

like image 864
BadHorsie Avatar asked Jul 12 '12 10:07

BadHorsie


People also ask

Does Base64 include slashes?

No. The Base64 alphabet includes A-Z, a-z, 0-9 and + and / . You can replace them if you don't care about portability towards other applications.

What characters are allowed in Base64?

Base64 only contains A–Z , a–z , 0–9 , + , / and = . So the list of characters not to be used is: all possible characters minus the ones mentioned above. For special purposes .

What is Base64 URL?

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.

Can Base64 contain underscore?

The suggestion was Base64 encoding. This has worked fine until recently when we needed to use Azure blob storage, which does not allow underscores "_" in it's directory (Container) names.


2 Answers

No. The Base64 alphabet includes A-Z, a-z, 0-9 and + and /.

You can replace them if you don't care about portability towards other applications.

See: http://en.wikipedia.org/wiki/Base64#Variants_summary_table

You can use something like these to use your own symbols instead (replace - and _ by anything you want, as long as it is not in the base64 base alphabet, of course!).

The following example converts the normal base64 to base64url as specified in RFC 4648:

function base64url_encode($s) {     return str_replace(array('+', '/'), array('-', '_'), base64_encode($s)); }  function base64url_decode($s) {     return base64_decode(str_replace(array('-', '_'), array('+', '/'), $s)); } 
like image 129
Artefact2 Avatar answered Sep 21 '22 22:09

Artefact2


In addition to all of the answers above, pointing out that / is part of the expected base64 alphabet, it should be noted that the particular reason you saw a / in your encoded string, is because when base64 encoding ASCII text, the only way to generate a / is to have a question mark in a position divisible by three.

like image 28
Snorbuckle Avatar answered Sep 21 '22 22:09

Snorbuckle