Encode URL from C #, decode URL in PHP (additional characters are added)

I already read so many topics on this issue, I canโ€™t understand where this problem could lie. I am encrypting part of the url from a winform C # application. Then I want to read the url using php and decrypt the url (everyone uses base-64). I have some code for shrae:


Code for URL Encryption (C #):

public static string Base64Encode(string str) { byte[] encbuff = Encoding.UTF8.GetBytes(str); return System.Web.HttpServerUtility.UrlTokenEncode(encbuff); } 

Decrypt URL section:

 Base64Encode("CND0311J4S68CCU Ver. F.0BHPQOEM - f"); 

Returns:

 Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1 


URL decryption code (PHP):

 echo base64_decode("Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1"); 

Return:

 CND0311J4S68CCU Ver. F.0BHPQOEM - f5 

So where is the extra โ€œ5โ€ at the end of the return? I can't figure it out for a life of me that is pretty disappointing, as you might imagine.

I appreciate any help with this - and any suggestions!

Thank,

Evan

+2
c # url php base64
Sep 16 '11 at 18:06
source share
2 answers
 "CND0311J4S68CCU Ver. F.0BHPQOEM - f" 

encoded as base64:

 Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1 

Maybe something else adds 1 to the end, because

 echo base64_decode("Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY"); 

gives you what you are looking for. And something adding it actually System.Web.HttpServerUtility.UrlTokenEncode . The problem is the following ( from MSDN ):

This ( System.Web.HttpServerUtility.UrlTokenEncode ) does not use standard encoding. It encodes the characters - and _, which are standard. It also removes the = signs. But instead of just deleting them (they are not needed to decode the string), he replaces them with a digit (0, 1, 2) indicating the number = of characters that were deleted.

So go ( Demo ):

 <?php $urltoken = "Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY1"; echo urltoken_decode($urltoken); function urltoken_decode($token) { return base64_decode(substr($token, 0, -1)); } 

The function is pretty crude and can 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)); } 
+4
Sep 16 '11 at 18:12
source share

Interesting - when I encode "CND0311J4S68CCU Ver. F.0BHPQOEM - f" to this site (using JavaScript), it is encoded as "Q05EMDMxMUo0UzY4Q0NVIFZlci4gRi4wQkhQUU9FTSAtIGY," If I decode "Q05EMQIFiXYU, I get QUIQIQxQYQYQYQYQXIQYQYQYXYY. Apparently, the problem is the end of the encoding - perhaps try to print the value you encode before it is passed to the base64 codec to make sure that this is exactly what you think?

0
Sep 16 '11 at 18:14
source share



All Articles