Az.Youness
Az.Youness

Reputation: 2652

Generate encrypted string that can be used directly in URLs

Sometimes in my forms I found my self using hidden inputs that contains some values that no need for client to know about it. (In effect even if he know is not a big problem, however I don't prefer that ... and that's way I don't need a very secure and complicated encryption stuff)

Based on some answers here (especially this), I build this next Class

class Crypto
{

    const ENCRYPT_METHODE = "AES-256-CBC";
    const SECRET_HASH     = "25c6c7ff35b9979b151f2136cd13b0ff";

    private static function GetIV()
    {

        if (empty($_SESSION['crypto']['iv'])) {
            $iv_size                  = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
            $_SESSION['crypto']['iv'] = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        }
        return $_SESSION['crypto']['iv'];
    }

    public static function Encrypt($value)
    {
        return openssl_encrypt($value,
            self::ENCRYPT_METHODE,
            self::SECRET_HASH,
            0,
            self::GetIV());
    }

    public static function Decrypt($value)
    {
        return openssl_decrypt($value,
            self::ENCRYPT_METHODE,
            self::SECRET_HASH,
            0,
            self::GetIV());
    }
}

... until now Crypto work's good with hidden input, but sometimes it generate strings that needs to be encoded before put it in a url

So, how to improve this class to do what I need ?
or is there an other better way to encrypt<=>decrypt strings?


EDIT
Instead of trying to generate a valid URL string value (directly with openssl_decrypt), it looks that adding urlencode / urldecode to methods will work just fine, and that's how Crypto methods will looks like:

class Crypto{

     // ...

    public static function Encrypt($value){
        $encrypted = openssl_encrypt($value,
                               self::ENCRYPT_METHODE,
                               self::SECRET_HASH,
                               0,
                               self::GetIV());

        return urlencode($encrypted);
    }

    public static function Decrypt($value){
        $value = urldecode($value);
        return openssl_decrypt($value,
                               self::ENCRYPT_METHODE,
                               self::SECRET_HASH,
                               0,
                               self::GetIV());
    }
}

I think like that it will work fine everywhere, Thanks to this answer

Upvotes: 0

Views: 2714

Answers (1)

Ad5001
Ad5001

Reputation: 753

You could use url_encode() to make sure every chars could be passed to an url and urldecode() to get the chars back.

Upvotes: 3

Related Questions