PHP Encrypt Decrypt a Request Param

I was looking for a way to encrypt a parameter in a URL. I found some nice and handy solutions but then I discovered that most of them are using mcrypt extension is deprecated (mcrypt_encrypt and mcrypt_decrypt).

The best solution now is to use the two way encryption openssl extension.
The following is a basic and simple PHP class for encrypting and decrypting a string in order to send it as a request parameter in a URL.

PHP openssl simple class for encrypting and decrypting a string

class SA_Encryption{
    const OPEN_SSL_METHOD = 'aes-256-cbc';
    // Generate a 256-bit encryption key
    const BASE64_ENCRYPTION_KEY = 'G1fM0aXhguJ5tVaqVMJOVHB+Jk6QFd99FgkfAcEgwjI';//base64_encode(openssl_random_pseudo_bytes(32));
    const BASE64_IV = 'xIkaHuquZFjtP4SI4mIyOg';//base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC)));
    static private function base64_url_encode($input) {
        return strtr(base64_encode($input), '+/=', '-_,');
    static private function base64_url_decode($input) {
        return base64_decode(strtr($input, '-_,', '+/='));
    static function encrypt_to_url_param($message){
        $encrypted = openssl_encrypt($message, self::OPEN_SSL_METHOD, base64_decode(self::BASE64_ENCRYPTION_KEY), 0, base64_decode(self::BASE64_IV));
        $base64_encrypted = self::base64_url_encode($encrypted);
        return $base64_encrypted;
    static function decrypt_from_url_param($base64_encrypted){
        $encrypted = self::base64_url_decode($base64_encrypted);
        $decrypted = openssl_decrypt($encrypted, self::OPEN_SSL_METHOD, base64_decode(self::BASE64_ENCRYPTION_KEY), 0, base64_decode(self::BASE64_IV));
        return $decrypted;

Base64_url has some non friendly URL characters hence I replaced them with other chars. One can use url_encode function but it can triple the string length.


 //==== for sending param ====
$send_time = time();
$user = array('user','pass', $send_time );
$message = implode('||', $user);
$param = SA_Encryption::encrypt_to_url_param($message);
//==== for receiving param ====
$message = SA_Encryption::decrypt_from_url_param($param);
$user = explode('||', $message);
$receive_time = time();
$diff = $receive_time - $user[2];
if ($diff > (2 * 24 * 60 * 60)){
    echo "expired token\n";
Leave a Reply