Best way to encode binary data into URL-safe string
TL;DR
Use base64url.
- RFC: https://datatracker.ietf.org/doc/html/rfc4648#section-5
- Wikipedia: https://en.wikipedia.org/wiki/Base64#Variants_summary_table
base64url is a base64 variant, replacing + and / in the original version with - and _ and removing the padding (=).
Why?
The URL-safe characters are [A-Za-z0-9-._~] including 66 characters, which means URL-safe string can encode and hold 6 bits data per char (2^6 = 64).
This StackOverflow answer refers to the section 2.3 of RFC 3986 that says the URL-safe characters (“Unreserved Characters”) are
unreserved = ALPHA / DIGIT / ”-” / ”.” / ”_” / ”~”
ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39)
is
ALPHA (A-Z and a-z), DIGIT (0-9)
What is the smallest URL friendly encoding? (StackOverflow)