Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a large number (in an URL)?

Tags:

http

url

encoding

Quite often one has to encode an big (e.g. 128 or 160 bits) number in an url. For example many web applications use md5(random()) for UUIDs.

If you need to put that value in an URL the common approach is to just encode it as an hexadecimal string.

But obviously hex encoding is not a very tight encoding. What other approaches are there which fit nicely in an URL?

like image 323
max Avatar asked Jan 24 '23 21:01

max


1 Answers

I would use The "URL and Filename safe" Base 64 Alphabet.

Base 64 uses two character sets.

Data: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
URLs: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_

To use base 64 you need to pad your value to be a multiple of 3 bytes long (24 bits) then split those 24 bits into 4 6bit bytes. Each 6bit value is looked up by position in the string I gave above.

If it all goes well, your final base64 value will always be a multiple of 4 characters long and decode back to a multiple of 3 (8bit) bytes long.

Depending on the language you are using, a lot of them have built in encode and decode functions.

like image 128
John Avatar answered Jan 26 '23 11:01

John