In JavaScript, how can i decode a string that was encoded in C# using HttpServerUtility.UrlTokenEncode
?
There are some equivalents in other languages but i couldn't rewrite them in JS. Any help would be appreciated.
This is the Java version.
This is the Objective-C version.
C#'s URLTokenEncode
is not the same as base64 encoding. For example the last character is always the number of padding characters. So some characters need to be replaced properly. Java and Objective-C version of the code show which characters need to be replaced with what.
I tried decodeURIComponent
but it was not decoded successfully. That makes sense because the string is encoded by a particular method. It's not base64.
For example, This is just a part of a C#'s UrlTokenEncode
String:
vj4_fv7__7-_Pr6-ff3_Pr6_vz8_________________f____79_vP1_vb3_vz8____________________AAA1
And this is the correct decoded version using Objective-C/Java method:
vj4/fv7//7+/Pr6+ff3/Pr6/vz8/////////////////f////79/vP1/vb3/vz8////////////////////AAA=
I finally managed to convert the Objective-c version of URLTokenDecode
by Jeffrey Thomas to JavaScript and it worked.
Here is the function:
function URLTokenDecode(token) {
if (token.length == 0) return null;
// The last character in the token is the number of padding characters.
var numberOfPaddingCharacters = token.slice(-1);
// The Base64 string is the token without the last character.
token = token.slice(0, -1);
// '-'s are '+'s and '_'s are '/'s.
token = token.replace(/-/g, '+');
token = token.replace(/_/g, '/');
// Pad the Base64 string out with '='s
for (var i = 0; i < numberOfPaddingCharacters; i++)
token += "=";
return token;
}
Here is the $filter if you are using AngularJS:
app.filter('URLTokenDecode', function () {
return function (token) {
if (token.length == 0) return null;
// The last character in the token is the number of padding characters.
var numberOfPaddingCharacters = token.slice(-1);
// The Base64 string is the token without the last character.
token = token.slice(0, -1);
// '-'s are '+'s and '_'s are '/'s.
token = token.replace(/-/g, '+');
token = token.replace(/_/g, '/');
// Pad the Base64 string out with '='s
for (var i = 0; i < numberOfPaddingCharacters; i++)
token += "=";
return token;
}
});