What is the difference between Convert.ToBase64String (byte []) and HttpServerUtility.UrlTokenEncode (byte [])?

I am trying to remove the dependency on System.Web.dll from a web API project, but stumbled upon a call to HttpServerUtility.UrlTokenEncode(byte[] input) (and its corresponding decoding method), which I do not know what to replace in order to provide backward compatibility. The documentation states that this method

Encodes an array of bytes into its equivalent string representation, using base 64 digits that can be used to pass to a URL.

I tried replacing Convert.ToBase64String(byte[] input) (and its corresponding decoding method), which is very similarly described in the docs:

Converts an array of 8-bit unsigned integers to its equivalent string representation, which is encoded with base-64 digits.

However, they do not seem completely equivalent; when using Convert.FromBase64String(string input) to decode a string encoded with HttpServerUtility , I get an exception indicating

The input is not a valid Base-64 string because it contains a non-base 64 character, more than two padding characters, or an invalid character among padding characters.

What is the difference between these two conversion utilities? What is the correct way to remove this dependency on System.Web.HttpServerUtility ?


Some users have suggested that this is a duplicate of this , but I disagree. This question is related to base-64-encoded string in the form of url-safe in general, but I need to reproduce the exact behavior of HttpServerUtility , but without dependence on System.Web .

+5
source share
2 answers

I took DGibbs to their word and used Source . It turns out that the following happens in the HttpServerUtility methods:

Base64 encoding

  • Use System.Convert to convert input to Base64.

  • Replace + with - and / with _ . Example: Foo+bar/=== becomes Foo-bar_=== .

  • Replace any number = at the end of the line with an integer indicating how many they were. Example: Foo-bar_=== becomes Foo-bar_3 .

Decoding from Base64

  • Replace the number at the end of the line with the same number of = signs. Example: Foo-bar_3 becomes Foo-bar_=== .

  • Replace - with + and _ with / . Example: Foo-bar_=== becomes Foo+bar/=== .

  • Use System.Convert to decode pre-processed input from Base64.

+9
source

HttpServerUtility.UrlTokenEncode(byte[] input) will encode a Base64 safe string. In Base64 +, / and = characters are valid, but they are not safe for URLs, this method will replace these characters, while Convert.ToBase64String(byte[] input) will not. You can probably opt out of the link and do it yourself.

Usually "+" is replaced by "-" and "/" by "_" padding '=', it is simply deleted.

The accepted answer here gives an example code: How to securely encode Base64 URLs in C #?

+3
source

Source: https://habr.com/ru/post/1243119/


All Articles