Home >Backend Development >C++ >How to Encode and Decode Modified Base64 URLs in ASP.NET Framework?

How to Encode and Decode Modified Base64 URLs in ASP.NET Framework?

Linda Hamilton
Linda HamiltonOriginal
2025-01-11 22:08:42878browse

How to Encode and Decode Modified Base64 URLs in ASP.NET Framework?

Encoding and decoding modified Base64 URLs in ASP.NET Framework

As defined by the "Modified Base64 for URLs" concept, decoding and encoding modified Base64 URLs can be implemented through custom code or by leveraging methods in the HttpServerUtility class.

Custom code

To perform modified Base64 encoding, you can use the following code:

<code class="language-csharp">// 执行正常的 base64 编码
byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText);
string base64EncodedText = Convert.ToBase64String(encodedBytes);

// 应用 URL 变体
string base64UrlEncodedText = base64EncodedText.Replace("=", "").Replace('+', '-').Replace('/', '_');</code>

For decoding, you can use the following code:

<code class="language-csharp">string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/');

// 根据需要追加“=”字符 - 最佳方法是什么?

// 我正常的 base64 解码现在使用 encodedText</code>

HttpServerUtility class

Alternatively, you can use the HttpServerUtility and UrlTokenEncode methods of the UrlTokenDecode class:

<code class="language-csharp">///<summary>
/// 使用 UTF-8 字符集进行 Base 64 编码,使用 URL 和文件名安全字母表。
///</summary>
///原始字符串
///<returns>Base64 编码的字符串</returns>
public static string Base64ForUrlEncode(string str)
{
    byte[] encbuff = Encoding.UTF8.GetBytes(str);
    return HttpServerUtility.UrlTokenEncode(encbuff);
}
///<summary>
/// 使用 UTF-8 解码使用 URL 和文件名安全字母表的 Base64 编码字符串。
///</summary>
///Base64 代码
///<returns>解码后的字符串。</returns>
public static string Base64ForUrlDecode(string str)
{
    byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
    return Encoding.UTF8.GetString(decbuff);
}</code>

Note 1: The output of the HttpServerUtility method is not a valid Base64 string because it replaces some characters with URL-safe characters.

Note 2: The output format of HttpServerUtility is different from the base64url algorithm in RFC4648 because it replaces '=' with '0', '1' or '2' depending on the number of equal signs replaced Padding to ensure URL security.

The above is the detailed content of How to Encode and Decode Modified Base64 URLs in ASP.NET Framework?. 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