Raymond Raymond

C#: Base64 URL Encoder and Decoder

event 2021-08-24 visibility 2,701 comment 0 insights toc
more_vert
insights Stats

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.

Result:

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

References

Base64UrlEncoder Class (Microsoft.IdentityModel.Tokens) - Azure for .NET Developers | Microsoft Docs

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts