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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-25 03:17:09355browse

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

The URL security base64 encoding

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>

Comparison with the CODEC library

<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!

Statement:
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