Base64 in .NET

If you work with network systems enough, you'll eventually run into base64 encoding. This shows up in many places, from email attachments to JWT tokens. Wikipedia has a very decent description. Even in this short blog I've already brought it up before.

.NET has had a Convert.FromBase64String and Convert.ToBase64String since very early days, and of course their array-based counterparts.

These days, you are likely to run into things like WebEncoders.Base64UrlDecode for example. What's the difference?

Basically, the code in WebEncoders provides much more flexibility, accounting for things you'll see in practice, like non-padded entries, or alternate encodings. However, it's simply layered on top of the prior APIs - you can see in the implementation that after all the fixups, it simply bottoms up by calling into FromBase64CharArray.

And now you know - use WebEncoders, unless you have some reason to believe your input is super clean, or be prepared to reimplement those checks!

Happy encoding and decoding!

Tags:  codingdotnet

Home