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:
<code class="language-csharp">string returnValue = System.Convert.ToBase64String(toEncodeAsBytes) .TrimEnd(padding).Replace('+', '-').Replace('/', '_');</code>
<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>
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!