C#: Base64 URL Encoder and Decoder

visibility 8 comment 0 access_time 25 days ago

Base64 is commonly used to encode binary data. When using it 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);

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
I am the original text.

Add the package

Run the following command to add the package:

dotnet add package Microsoft.IdentityModel.Tokens


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

copyright This page is subject to Site terms.

Subscribe newsletter

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext

visibility 686
thumb_up 0
access_time 2 years ago
visibility 44
thumb_up 0
access_time 10 months ago