Home > Backend Development > C++ > How to Implement URL-Safe Base64 Encoding in C#?

How to Implement URL-Safe Base64 Encoding in C#?

Susan Sarandon
Release: 2025-01-25 03:12:09
Original
362 people have browsed it

How to Implement URL-Safe Base64 Encoding in C#?

URL safe Base64 encoding in C#

In the field of data transmission, Base64 encoding plays a vital role in converting binary data into text representations that can be transmitted securely over various communication channels. However, standard Base64 encoding can cause problems when passing data through URLs due to the presence of reserved and padding characters. To solve this problem, URL safe Base64 encoding came into being.

Comparison of Java and C#

In Java, the commonly used Codec library provides a convenient way to implement URL-safe Base64 encoding. However, in C# one might wonder how to replicate this functionality.

Solution

C# provides a straightforward solution to implement URL-safe Base64 encoding without relying on external libraries. This involves two key steps:

  1. Replace problematic characters: The characters " ", "/", and "=" are reserved characters in URLs and may cause decoding errors. To avoid this, we simply replace " " with "-", "/" with "_", and remove the padding character "==".
<code class="language-csharp">string returnValue = System.Convert.ToBase64String(toEncodeAsBytes)
        .TrimEnd(padding).Replace('+', '-').Replace('/', '_');</code>
Copy after login
  1. Reverse process: To decode the URL-safe encoded string, we perform the reverse process, replacing "-" with " ", "_" with "/", and adding the appropriate filling.
<code class="language-csharp">string incoming = returnValue
    .Replace('_', '/').Replace('-', '+');
switch(returnValue.Length % 4) {
    case 2: incoming += "=="; break;
    case 3: incoming += "="; break;
}
byte[] bytes = Convert.FromBase64String(incoming);
string originalText = Encoding.ASCII.GetString(bytes);</code>
Copy after login

Custom method or external library?

One might question whether this approach is consistent with the approach used by the "Universal Codec Library" in Java. However, this is a common and reasonable technique that should provide the desired functionality in C#.

The above is the detailed content of How to Implement URL-Safe Base64 Encoding in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template