Base64 encoded, URL Safe, C#

Base64-encoded string URL Safe

5 min read

  • January 27,2025
  • Rajesh Goel

If you're passing a Base64-encoded string in a URL and encountering issues with special characters not being parsed correctly in C#, it's likely because Base64 encoding can include characters like +, /, and = that are not URL-safe. These characters can cause issues when transmitted as part of a URL.

Solution: Use URL-Safe Encoding

To make the Base64 string URL-safe, you need to:

  •  Replace the characters +, /, and = with URL-safe equivalents. 
  • Decode the string back on the server side.

 

Here’s how you can handle this:

1. Encoding to URL-Safe Base64 in C#:

using System;
using System.Text;

public class Program
{
   public static void Main()
   {
       string originalString = "encrypted string";
       
       // Convert to Base64
       string base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalString));
       
       // Make it URL-safe
       string urlSafeBase64 = base64String
           .Replace("+", "-") // Replace + with -
           .Replace("/", "_") // Replace / with _
           .Replace("=", ""); // Remove padding =

       Console.WriteLine("URL-Safe Base64: " + urlSafeBase64);
   }
}

 

2. Decoding the URL-Safe Base64 in C#:

using System;
using System.Text;

public class Program
{
   public static void Main()
   {
       string urlSafeBase64 = "Your-URL-Safe-Base64-String";
       
       // Make it Base64 compatible
       string base64String = urlSafeBase64
           .Replace("-", "+") // Replace - with +
           .Replace("_", "/") // Replace _ with /
           .PadRight(urlSafeBase64.Length + (4 - urlSafeBase64.Length % 4) % 4, '='); // Add padding if missing

       // Decode from Base64
       string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
       
       Console.WriteLine("Decoded String: " + originalString);
   }
}
 

3. Why URL-Safe Encoding is Necessary

  • + becomes - because + is a reserved character in URLs.
  • / becomes _ because / can be interpreted as a path delimiter.
  • = is removed because it is used for padding in Base64 but isn't URL-safe.

 

CONCLUSION

  • Always encode sensitive data before including it in URLs.
  • Test decoding thoroughly to ensure no data corruption.
  • Use libraries where possible for safer implementations:
    • Example: Use System.Web.HttpUtility.UrlEncode for encoding URLs if required.