xxxxxxxxxx
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
Base64 encoding/decoding will have unsafe url characters. Generally the best solution to this problem is url_encode/url_decode the base64 encoded string (most languages have simple method for url_encoding/decoding): what if we keep going so that there could be some overlap if we are not.
xxxxxxxxxx
$str = 'My String';
$encoded = urlencode(base64_encode($str));
$decoded = base64_decode( urldecode($encoded));
Another approach is to replace the url unsafe character when encoding then replace them back when decoding like so:
xxxxxxxxxx
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
Note: Most languages have some built in function for url safe base64 encoding/decoding.