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
Release: 2025-01-25 03:17:09
Original
360 people have browsed it

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:

string returnValue = System.Convert.ToBase64String(toEncodeAsBytes)
        .TrimEnd(padding).Replace('+', '-').Replace('/', '_');
Copy after login

To reverse this process:

static readonly char[] padding = { '=' };
Copy after login

Comparison with the CODEC library

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);
Copy after login

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