I’ve written some nice flexible standards based implementations of various Base32 and Base64 encoding/decoding methods. These are designed to encode binary data to plain text, and decode the resulting text back to the original binary. Useful when you need to transfer binary data through technologies that only support text (such as including binary security tokens in URLs).
The code is available up on codeproject.com
Base32Url encodes with only the characters A to Z and 2 to 7. No hyphens, underscores, pluses, slashes or equals are used, making it usable as a URL token in almost all circumstances. Base32Url also supports custom alphabets. A custom case sensitive alphabet with only consonant (non vowel) characters can be used to ensure your tokens do not contain accidental profanities. The following is an example that avoids vowels, the letter L and has no numeric characters:
Base64Url is more compact than Base32Url and it is almost always usable as a URL token or file-name. The only non alpha-numeric characters Base64Url contains are the hyphen (-) and underscore (_) characters, neither of these need further encoding for use in URLs or file-names.
Base32Url (Encoder / Decoder)
The default mode for the Base32 encoder/decoder is Base32Url. This uses the standard Base32 alphabet encoding but omits padding characters and is case insensitive.
Supports standard Base32 with padding characters (=) per Base32 from RFC 4648.
Supports the Base32 extension / alternate alphabet z-base-32
Base64Url (Encoder / Decoder)
Based on the standard .net Base64 encoder
Uses the URL-Safe alternative Base64 alphabet from RFC 4648
This is not the same as Microsoft’s
Further Information and Usage
There are other implementations of base32 encoding out there but I feel the code of this base32 implementation is much simpler (far less code involved in the bit shifting calculations).
The base64 implementation I have here is a little hackish, but a far better option than the one you get from Microsoft.
The result you get from
HttpServerUtility.UrlTokenEncode is essentially base64url, but instead of truncating the padding, they append a digit (of 0, 1 or 2) indicating the number of padding characters removed.
Usage: Base32Url.ToBase32String(Encoding.ASCII.GetBytes("Hello World!")); JBSWY3DPEBLW64TMMQQQ var b32 = new Base32Url(true); // Base32Url(bool usePadding) b32.Encode(Encoding.ASCII.GetBytes("Hello World!")); JBSWY3DPEBLW64TMMQQQ====
For more information about the standards involved please see rfc 4648 http://tools.ietf.org/html/rfc4648