ZendFramework - 如何使用Zend_Filter和bin2hex和hex2bin进行加密和解密?

时间:2011-12-21 21:12:43

标签: php zend-framework zend-filter

当我进行编码时,我有这个随机的“d9b3b2d69bab862a”值。但我无法将其解码回abcd。知道怎么做吗?

编码器/解码器运行:

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

ZF模型:

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;
  }  

}

1 个答案:

答案 0 :(得分:2)

如果你想使用bin2hex“编码”二进制数据,以便通过http / url轻松传输,你可以采取以下措施将其反转回二进制数据:

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

您班级的其他小问题是对$key$vector的引用。 由于这两种方法都是静态的,因此无法访问$this$key,而且$vector未定义。

以下代码适合您:

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;
    }
}

或者,您可以在getEnc函数中使用base64_encode,在getDec函数中使用base64_decode。 Base64通常用于表示加密的二进制数据。