Search code examples
phparraysserializationbase64mcrypt

How to encrypt/encode an array in an url friendly format better than using serialize and base64


I'm currently using this code to generate an hyperlink in an .xls file from an intranet server.

This .xls file is an order I submit by email to one of my supplier.

/* WEBSERVER1 */  
$ORDER=$_GET['ORDER'];
$EZAB=$_GET['EZAB'];
$IP=$_GET['IP'];

$ARRAY = array(
    "ORDER" => $ORDER,
    "EZAB" => $EZAB,
    "IP" => $IP);

$SERIAL=serialize($ARRAY);
$q=base64_encode($SERIAL);
$URL="http://mywebsite/?q=".$q
$EXCELHYPERLINK='=hyperlink("'.$URL.'")';

I want my supplier to click on the link in the .xls file to confirm the order has been processed, instead of replying to the original email.

The intranet server not being accessible from the outside world, the link is pointing on a webserver hosting the following code.

/* WEBSERVER2 */
$q=$_GET['q'];
$SERIAL=base64_decode($q);
$ARRAY=unserialize($SERIAL);
// Do something...

I would rather prefer not to use database.

Do you have any thought on how i can make the content of the "$KEY" not that easy to find out?


Solution

  • mcrypt allows me to encrypt the data transmitted via GET. (thanks to @dAm2K)

    The base64_encode is not enough to make the encrypted date URL friendly as it include ("+","/" and "=" characters) (thanks to @DavidThomas)

    I used str_replace to replace those 3 characters and everything is working fine.

    Here's the corrected code for the intranet server:

    /* WEBSERVER1 */  
    $ORDER=$_GET['ORDER'];
    $EZAB=$_GET['EZAB'];
    $IP=$_GET['IP'];
    
    $ARRAY = array(
        "ORDER" => $ORDER,
        "EZAB" => $EZAB,
        "IP" => $IP);
    
    $SERIAL=serialize($ARRAY);
    $M=mcrypt_module_open('rijndael-256','','cbc','');
    $KEY=md5("gi7aesawde2zomspgo8guvivmer8oici");
    $IV=md5("dob1depatodop7lipdaig7bebeaion9d");
    mcrypt_generic_init($M,$KEY,$IV);
    $ENCRYPTEDDATA=mcrypt_generic($M,$SERIAL);
    mcrypt_generic_deinit($M);
    mcrypt_module_close($M);
    $q=base64_encode($ENCRYPTEDDATA);
    $q=str_replace(array('+','/','='),array('-','_','.'),$q);
    
    $URL="http://mywebsite/?q=".$q;
    $EXCELHYPERLINK='=hyperlink("'.$URL.'")';
    

    and for the webserver :

    /* WEBSERVER2 */
    $q=$_GET['q'];
    $q=str_replace(array('-','_','.'),array('+','/','='),$q);
    $ENCRYPTEDDATA=base64_decode($q);
    $M=mcrypt_module_open('rijndael-256','','cbc','');
    $KEY=md5("gi7aesawde2zomspgo8guvivmer8oici");
    $IV=md5("dob1depatodop7lipdaig7bebeaion9d");
    mcrypt_generic_init($M,$KEY,$IV);
    $SERIAL=mdecrypt_generic($M,$ENCRYPTEDDATA);
    mcrypt_generic_deinit($M);
    mcrypt_module_close($M);
    $ARRAY=unserialize($SERIAL);
    
    // Do something...