I would like to implement a simple substitution cipher to mask private ids in URLs.
I know how my IDs will look like (combination of uppercase ASCII letters, digits and underscore), and they will be rather long, as they are composed keys. I would like to use a longer alphabet to shorten the resulting codes (I’d like to use upper- and lowercase ASCII letters, digits and nothing else). So my incoming alphabet would be
[A-Z0-9_] (37 chars)
and my outgoing alphabet would be
[A-Za-z0-9] (62 chars)
so a compression of almost 50% reasonable amount of compression would be available.
Let’s say my URLs look like this:
/my/page/GFZHFFFZFZTFZTF_24_F34
and I want them to look like this instead:
/my/page/Ft32zfegZFV5
Obviously both arrays would be shuffled to bring some random order in.
This does not have to be secure. If someone figures it out: fine, but I don’t want the scheme to be obvious.
My desired solution would be to convert the string to an integer representation of radix 37, convert the radix to 62 and use the second alphabet to write out that number. is there any sample code available that does something similar? Integer.parseInt() has some similar logic, but it is hard-coded to use standard digit behavior.
Any ideas?
I am using Java to implement this but code or pseudo-code in any other language is of course also helpful.
Inexplicably
Character.MAX_RADIXis only 36, but you can always write your own base conversion routine. The following implementation isn’t high-performance, but it should be a good starting point:Then you can have a
main()test harness like the following:Some observations
BigIntegeris probably easiest if the numbers can exceedlongcharin the symbolString, just stick to one “secret” permutationNote regarding “50% compression”
You can’t generally expect the base 62 string to be around half as short as the base 36 string. Here’s
Long.MAX_VALUEin base 10, 20, and 30: