My app communicates with a third-party service that uses base64 encoding on their identifiers. I want to replicate their identifier encoding scheme to communicate with their system, but I'm getting mismatched identifies when the string has to be padded.
Our system is built on php. Using php's base64_encode() on a string that ends with '2~' that needs to be padded results in 'Mn4='. However, their system instead results in 'Mn5'. Both of these string are parsed by php's base64_decode() back into '2~'. I understand that some systems strip the trailing = but the 4 turns into a 5 as well.
In order to figure it out, I tried manually to convert the string to base64, based on wikipedia's Base64 examples:
- First, convert the characters into octals:
'2~'would become00110010 01111110
- Now take those and convert group into sextets:
- It would become
001100 100111 1110.
- It would become
- "When the last input group contains only two octets, all 16 bits will be captured in the first three Base64 digits (18 bits); the two least significant bits of the last content-bearing 6-bit block will turn out to be zero, and discarded on decoding"
- It would become
001100 100111 111000
- It would become
- Then convert into ascii using the Base64 table
- It would become
M n 4
- It would become
- Then add the zero padding with
=- It would become
Mn4=
- It would become
So where did the 5 come from? The 111000 sextet would have to be 111001 instead. Those bits are discarded on decode, which normally isn't a problem, but since they are storing/using the base64 as identifiers, this is causing mismatches in my system.
Is there any known implementation that does right padding with non-zeros? I didn't see any listed on Wikipedia's variant list. Can I replicate this behavior in php without rewriting base64_encode in php from scratch?