Michael Böckling
Michael Böckling

Reputation: 7872

How to encode and shorten hash for url safety?

I use SHA-512 to hash a token, which results in a 128 character string. How can I encode it so that it is shorter but still URL safe (no need to escape like '+' or '&')?

Hex and Base32 are both suboptimal, and Base64 is unsafe. I don't want to hack up a custom Base62 codec, as that will only become a maintenance burden.

Upvotes: 0

Views: 1706

Answers (2)

john16384
john16384

Reputation: 8054

Java 8 added Base64 encoders, with different flavors. See java.util.Base64

For example:

Base64.getUrlEncoder().encode(...);

Upvotes: 0

Michael Böckling
Michael Böckling

Reputation: 7872

Google has you covered:

com.google.common.io.BaseEncoding#base64Url

This is an efficient Base64 codec that only uses url-safe characters. It will produce a String with a length of 88 characters for a SHA512 hash.

Upvotes: 1

Related Questions