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

I have these random values โ€‹โ€‹"d9b3b2d69bab862a" when I encode. But I can not decode it before abcd . Any idea how to do this?

Encoder / Decoder Launch:

 $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; } } 
+4
source share
1 answer

If you want to use bin2hex to โ€œencodeโ€ binary data so that it can be easily transported via http / url, here is what you can do to undo it back to the binary:

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

Other minor issues with your class were links to $key and $vector . Since both methods are static, they cannot access $this and $key and $vector only 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 can use base64_encode in your getEnc function and base64_decode in your getDec function. Base64 is commonly used to represent binary data using encryption.

+2
source

Source: https://habr.com/ru/post/1387468/


All Articles