phpzend-frameworkzend-filter

ZendFramework - How to encrypt and decrypt using Zend_Filter with bin2hex and hex2bin?


I have this random "d9b3b2d69bab862a" values when i do encoding. But i can not decode it back to abcd. Any idea how to do it?

Encoder/Decoder run:

$tokenIs = Application_Model_Login::getEnc("abcd");
echo $tokenIs . "<br/><br/>";    
echo Application_Model_Login::getDec(hex2bin($tokenIs)); //hints: rawurldecode(..) works

ZF Model:

class Application_Model_Login
{
  private $key  = "thisisakeytolock";
  private $vector= "myvector";

  public static function getEnc($input)
  {   
    $filter = new Zend_Filter_Encrypt(array('adapter' => 'mcrypt', 'key' => $key));
    $filter->setVector($vector);
    $encrypted = $filter->filter($input);
    // bin2hex for user use case     
    return bin2hex($encrypted); //hints: rawurlencode(..) works
  }

  public static function getDec($input)
  {

    $filter = new Zend_Filter_Decrypt(array('adapter' => 'mcrypt', 'key' => $key));
    $filter->setVector($this->vector);
    $encrypted = $filter->filter($input);    
    return $encrypted;
  }  

}

Solution

  • If you want to use bin2hex to "encode" the binary data so it is easily transported over http/url, here is what you can do to reverse it back to binary:

    $encoded = bin2hex($some_binary);
    $decoded = pack('H*', $encoded);
    

    Other minor issues with your class was the references to $key and $vector. Since both methods are static, they cannot access $this and $key and $vector alone are undefined.

    The following code should work for you:

    class Application_Model_Login
    {
        const ENC_KEY = "thisisakeytolock";
        const VECTOR  = "myvector";
    
        public static function getEnc($input)
        {
            $filter = new Zend_Filter_Encrypt(array('adapter' => 'mcrypt', 'key' => self::ENC_KEY));
            $filter->setVector(self::VECTOR);
            $encrypted = $filter->filter($input);
            return bin2hex($encrypted); //hints: rawurlencode(..) works
            return $encrypted;
        }
    
        public static function getDec($input)
        {
    
            $filter = new Zend_Filter_Decrypt(array('adapter' => 'mcrypt', 'key' => self::ENC_KEY));
            $filter->setVector(self::VECTOR);
            $decoded = pack('H*', $input);
            $decrypted = $filter->filter($decoded);
            return $decrypted;
        }
    }
    

    Alternatively, you could use base64_encode in your getEnc function, and base64_decode in the getDec function. Base64 is commonly used to represent binary data from encryption.