Home >Backend Development >C++ >How to Implement URL-Safe Base64 Encoding and Decoding in C#?
Base64 encoding is a common encoding method, but when URL security coding is performed, some characters (,/, and =) may cause problems. Although Java's CodeC library provides a direct solution, C# requires a little different ways.
Implement URL security coding
To implement the URL security base64 encoding in C#, you can simply replace the problematic characters to URL-friendly characters (-replacement, _ replacement /), and delete any filling character (=).
Among them, padding is defined as:
<code class="language-csharp">string returnValue = System.Convert.ToBase64String(toEncodeAsBytes) .TrimEnd(padding).Replace('+', '-').Replace('/', '_');</code>
To reverse this process:
<code class="language-csharp">static readonly char[] padding = { '=' };</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>
It is worth noting that this method is similar to the method of using the CODEC library of Java. However, it is recommended to test this assumption to ensure that it is compatible with specific libraries in use.
The above is the detailed content of How to Implement URL-Safe Base64 Encoding and Decoding in C#?. For more information, please follow other related articles on the PHP Chinese website!