nette / utils

🛠 Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
https://doc.nette.org/utils
Other
1.98k stars 147 forks source link

Strings: add base64UrlEncode() and base64UrlDecode() #287

Open milo opened 1 year ago

milo commented 1 year ago

Base64 encoding is well known. It uses alphabet of 64 chars A-Z a-z 0-9 + / and padding char =. While the A-Z a-z 0-9 chars are URL safe, the remaining + / = are not. So there is a "Base 64 Encoding with URL and Filename Safe Alphabet" as mentioned in RFC4648. This encoding replaces + by - and / by _ and drops = padding.

The base64Url encoding is for example used by JSON Web Tokens (JWT), which are used for example in Open ID Connect protocol.

The implementation is based on Appendix C of IETF draft.

dg commented 1 year ago

I didn't get it at all :) What does it mean that something is not url safe?

milo commented 1 year ago

It is from mentioned RFC :) My opinion...

They wanted to transfer data via URL, but the rawurlencode("+/=") === '%2B%2F%3D' - these 3 chars from base64 alphabet have to be escaped and moreover, result is longer. So they brought -_ replacements which are not escaped. From my point of view it is a bad idea to insert something directly into URL, the rawurlencode() should be always used.

I'm working with JSON Web Tokens on a 4th project this year and content of the token is base64url encoded. So I thought, that base64 decode/encode can be useful for other people. But there are no 👍 reactions so maybe I'm alone :)