-
-
Save nathggns/6652997 to your computer and use it in GitHub Desktop.
<?php | |
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)); | |
} |
i think should be:
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) + 4 - (strlen($data) % 4), '=', STR_PAD_RIGHT));
}
What lp0 said is correct -- you don't need to pad the string before decoding it. Thus, the decode function should really be:
function base64url_decode($data) {
return base64_decode(strtr($data, '-_', '+/'));
}
I've unit tested this.
Since base64_decode() does not bother about "=" signs at the end, you can omit str_pad(..) as remarked by lp0 and mnpenner above.
However, if one will do the padding "manually" (for what reason ever), the pad_length in str_pad() should look like: strlen($data) + (4 - strlen($data) % 4) % 4
. @xsddz: Your code is close, but the case when strlen($data) % 4 = 0 should not insert any "=" at the end (your code appends 4x "=" in this case).
is there update on this with php >= 7?
https://www.php.net/manual/en/function.base64-encode.php#123098
why fiddle with base64 why dont you just pass it on rawurlencode/rawurldecode?
Thks!