tags:

views:

159

answers:

1

Below is my current encryption function.

define('ENCRYPT_KEY', 'ldkKKmeJddeFffKdjeddd'); 

function market_dock_api_encrypt($string) {
        $key = ENCRYPT_KEY; //preset key to use on all encrypt and decrypts.
        $result = '';
   for($i=0; $i<strlen($string); $i++) {
     $char = substr($string, $i, 1);
     $keychar = substr($key, ($i % strlen($key))-1, 1);
     $char = chr(ord($char)+ord($keychar));
     $result.=$char;
   }
   return urlencode(base64_encode($result));
}

I just realised that this sometimes results in keys with characters such as "%" in it, and I need a key that I can use in URLs. How can I change this to allow for that? I was under the impression that that's what the base64_encode part does. Obviously, I'm wrong.

+1  A: 

The string returned is safe to use in URLs - the "%"s come from it being passed through urlencode(). The base64_encode() was designed to pass binary data through ASCII, not specifically for URLs, so it can use "=", "+" and "/".

From the function comments:

This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

<?php
function base64url_encode($plainText)
{
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/', '-_');
    return ($base64url);    
}
?>

You may wish to rtrim (or escape) trailing ='s for use in a URI.

If you use this you'd obviously have to create a decoder as well.

Greg
The string is not safe to use, as i result with, for example, the following : "zdrK2ou%2B4cyv09bMq9nUrNHTx83Fks%2FT2A%3D%". this is a real example, and not good. So again, why am I ending up with a link like this (with % signs in it)?
RD
That *is* safe to use - the %'s make it safe
Greg
well, when i use it like yay: www.mysite.com/?c=zdrK2ou%2B4cyv09bMq9nUrNHTx83Fks%2FT2A%3D% it doesnt work. any idea what I'm missing?
RD
errr what doesn't work about it? Looks ok to me
Greg
Oh except you have a trailing % for some reason - did it get truncated? It should probably end in %3D%3D
Greg