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

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

Patricia Arquette
Patricia ArquetteOriginal
2025-01-25 03:21:13824browse

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

Base64 URL security coding in the c#

Question:

How to implement the Base64 URL security encoding in C#, where the '' 'and'/'characters are replaced by'-'and' _ ', and omit the filling' = '?

Answer:

In Java, the commonly used CODEC library can easily provide URL security coding. However, in C#, we need to realize our own solutions. Code:

To encode the byte array to the URL security Base64 string in C#, please use the following code:

Create a constant array for filling characters:

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

Decoding the URL security Base64 string decoding the Back byte array, please use the following code:
<code class="language-csharp">static readonly char[] padding = { '=' };</code>

Additional description:

In order to ensure that the URL security encoding provided by the Java Codec library is worth testing whether the above methods have produced the same results. URL security coding is a standard approach that can avoid%-encoding in the URL while maintaining the integrity of data.

The above is the detailed content of How to Implement Base64 URL-Safe 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