Encode URL from C#, decrypt URL in PHP (extra characters being added somehow)
I have read so many topics on this very subject by now, I can't understand where the issue could possibly lie. I am encrypting part of a URL from a C# winform application. I then want to read in the URL using php and decrypt the url (all using base-64). I do have some code to shrae:
Code to encrypt URL (C#):
public static string Base64Encode(string str)
{
byte[] encbuff = Encoding.UTF8.GetBytes(str);
return System.Web.HttpServerUtility.UrlTokenEncode(encbuff);
}
Decrypt a section of the URL:
Base64Encode("CND0311J4S68CCU Ver. F.0BHPQOEM - f");
Returns:
Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1
Code 开发者_开发问答to decrypt URL (PHP):
echo base64_decode("Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1");
Returns:
CND0311J4S68CCU Ver. F.0BHPQOEM - f5
So, where is the extra "5" at the end of the return coming from? I cannot figure this out for the life of me, quite frustrating as you could imagine.
I appreciate any help with this - as well as any suggestions!
Thank you,
Evan
"CND0311J4S68CCU Ver. F.0BHPQOEM - f"
encoded as base64 is not:
Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1
Probably something else is adding the 1
at the end, because
echo base64_decode("Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY");
gives you what you're looking for. And that something adding it is in fact System.Web.HttpServerUtility.UrlTokenEncode
. The issue is the following (from MSDN):
This (
System.Web.HttpServerUtility.UrlTokenEncode
) does not use a standard encoding. It encodes with - and _ characters which is standard. It also removes the = signs. But rather than simply removing them (they're not necessary to decode the string), it replaces them with a digit (0, 1, 2) indicating the number of = signs that were removed.
So go for it (Demo):
<?php
$urltoken = "Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1";
echo urltoken_decode($urltoken);
function urltoken_decode($token)
{
return base64_decode(substr($token, 0, -1));
}
The function is pretty rough and could be improved to actually deal with it more specifically (Demo2):
function urltoken_decode($token)
{
$len = strlen($token);
if (!$len)
return $token;
$digit = $token[$len-1];
if (!in_array($digit, range(0,2)))
{
throw InvalidArgumentException(sprintf('Invalid end digit (%s).', $digit));
}
return base64_decode(substr($token, 0, -1));
}
Interesting - when I encode "CND0311J4S68CCU Ver. F.0BHPQOEM - f" at this site (using JavaScript) it encodes as "Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY". If I decode "Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1" I get the extra 5 on the end. Apparently the problem is on the encoding end - maybe try outputting the value you're encoding just before it's passed to the base64 encoder to make sure it's exactly what you think it is?
精彩评论