Home > Backend Development > C++ > How to Perform URL-Safe Base64 Encoding and Decoding in ASP.NET?

How to Perform URL-Safe Base64 Encoding and Decoding in ASP.NET?

Patricia Arquette
Release: 2025-01-11 22:01:47
Original
266 people have browsed it

How to Perform URL-Safe Base64 Encoding and Decoding in ASP.NET?

URL Safe Base64 Encoding/Decoding in ASP.NET Framework

Base64 encoding is commonly used to encode binary data into a text format for transmission over a network. However, the standard Base64 encoding contains characters (especially " " and "/") that may interfere with URI templates and URLs.

To solve this problem, a modified version of Base64 encoding exists specifically for URLs. In this variant, " " and "/" are replaced by "-" and "_" respectively, and the padding character "=" is omitted.

Implementing a modified version of Base64 for URLs in the ASP.NET framework can use the following method:

Decoding:

  1. Replace "-" with " " and "_" with "/" in Base64 encoded text.
  2. Determine the number of missing "=" characters based on the length of the Base64 encoded text.
  3. Append the required "=" characters to the Base64 encoded text.
  4. Performs regular Base64 decoding on modified Base64 encoded text.

Encoding:

  1. Perform regular Base64 encoding on the raw data.
  2. Replace the "=" characters with the appropriate number of "0", "1" or "2" depending on the length of the Base64 string.
  3. Replace " " with "-" and "/" with "_".

Alternative:

.NET Framework provides the HttpServerUtility class, which contains the UrlTokenEncode and UrlTokenDecode methods that handle URL-safe Base64 encoding and decoding.

Code:

<code class="language-csharp">// 编码
string base64UrlEncodedText = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(plaintext));

// 解码
string plaintext = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(base64UrlEncodedText));</code>
Copy after login

Note: HttpServerUtility method returns a non-standard base64url implementation in which the "=" padding character is replaced with "0", "1" or "2". This is different from the RFC4648 standard, which uses the "=" character for padding.

The above is the detailed content of How to Perform URL-Safe Base64 Encoding and Decoding in ASP.NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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