C#: Base64 URL Encoder and Decoder
Base64 is commonly used to encode binary data. When using it in web application URLs, it is important to encode and decode it properly as there are three special characters used in the encoding: +, / and =. These three characters can be parsed differently in URLs.
Encode and decode code snippet
The following code snippet encode and then decode a string using utility class Microsoft.IdentityModel.Tokens.Base64UrlEncoder:
using Microsoft.IdentityModel.Tokens; var originalText = "I am the original text."; var encoded = Base64UrlEncoder.Encode(originalText); var decoded = Base64UrlEncoder.Decode(encoded); Console.WriteLine(encoded); Console.WriteLine(decoded);
The encode function performs base64url encoding which differs from regular base64 encoding as follows
- padding is skipped so the pad character '=' doesn't have to be percent encoded
- the 62nd and 63rd regular base64 encoding characters ('+' and '/') are replace with ('-' and '_')
These changes make the encoding alphabet file and URL safe.
dotnet run SSBhbSB0aGUgb3JpZ2luYWwgdGV4dC4 I am the original text.
Add the package
Run the following command to add the package:
dotnet add package Microsoft.IdentityModel.Tokens