天天看點

YII2架構安全篇

YII2架構真的是一款十分強大的架構,相對于TP和CI來說,功能更加完善,更加安全

那麼我們在功能完成的同時,安全是重中之重

下面我們就來看看YII架構中有哪些加密的方法!!

1、首先我們在做使用者密碼加密的時候我們一般都會采用md5來進行加密,在YII2架構中有一個加密方式比md5更加複雜

     //哈希加密

$password="123";
  $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
    // var_dump($hash);
    //$2y$13$Jxhmtb7XE8TxSs4cxBcJuug9a0U00AMyCnnG3JMNfSZcsUx.cfYYe      

  同時YII2架構中還有驗證pwd方法

$password="123";
$hash="$2y$13$Jxhmtb7XE8TxSs4cxBcJuug9a0U00AMyCnnG3JMNfSZcsUx.cfYYe";
if (Yii::$app->getSecurity()->validatePassword($password,$hash)){
           echo "yes";
}else {    
           echo "no";
}      

2、YII2架構中也有這自己的加密和解密方法

$secretKey="haiyong";
$data="123";
   //加密
   $encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
  //解密
  $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
  var_dump($data);      

3、還有随機數生成方法

$key = Yii::$app->getSecurity()->generateRandomString();      

我們不難看出來這些都是調用應用下的   getSecurity()方法 那麼這個方法在哪裡?

  目錄 vendor/yiisoft/yii2/base/Application.php 中

/**
 * Returns the security component.
 * @return \yii\base\Security the security application component.
 */
public function getSecurity()
{
    return $this->get('security');
}      

這個security是目前目錄下 Security.php(安全)中

有興趣的朋友可以試着研究其中的加密方式哦!!