Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to remove a dependence on System.Web.dll from a Web API project, but have stumbled on a call to HttpServerUtility.UrlTokenEncode(byte[] input) (and its corresponding decode method) that I don't know what to replace with to ensure backwards compatibility. The documentation says that this method

Encodes a byte array into its equivalent string representation using base 64 digits, which is usable for transmission on the URL.

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

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

However, they don't seem to be entirely equivalent; when using Convert.FromBase64String(string input) to decode a string encoded with HttpServerUtility, I get an exception stating

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

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


Some users have suggested that this is a duplicate of this one, but I disagree. That question is about base-64-encoding a string in a url-safe manner in general, but I need to reproduce the exact behavior of HttpServerUtility but without a dependency on System.Web.

like image 852
Tomas Aschan Avatar asked Feb 16 '16 10:02

Tomas Aschan


People also ask

What is UrlTokenEncode?

The UrlTokenEncode method converts a byte array into an equivalent string representation encoded with base 64 digits. The resulting string token can be transmitted on the URL. The UrlTokenEncode will return an empty string if the input parameter has a length of less than one.

What is ToBase64String?

ToBase64String(Byte[], Base64FormattingOptions) Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits. You can specify whether to insert line breaks in the return value.


1 Answers

HttpServerUtility.UrlTokenEncode(byte[] input) will encode a URL safe Base64 string. In Base64 +, / and = characters are valid, but they are not URL safe, this method will replace these characters whereas the Convert.ToBase64String(byte[] input) will not. You can probably drop the reference and do it yourself.

Usually, '+' is replaced with '-' and '/' with '_' padding '=' is just removed.

Accepted answer here gives a code example: How to achieve Base64 URL safe encoding in C#?

like image 179
MaxJ Avatar answered Sep 20 '22 13:09

MaxJ