如何在Yii2中使用Yii :: $ app-> security-> encryptByKey()保存加密数据

时间:2015-03-22 06:14:27

标签: php yii yii2

这是模特。

public function genCode($width = 15)
{   
    $inputKey = $this->password();
    $string = Yii::$app->security->generateRandomString($width);
    $this->_encrypted = Yii::$app->security->encryptByKey( $string, $inputKey );
    // $decrypted = Yii::$app->security->decryptByKey( $encrypted, $inputKey, $info = null );
    return $this->_encrypted;
}

public function saveCodeSample()
{
    $code = new Code;
    $code->type = 'sample';
    $code->owner_id = 1;
    $code->value = $this->genCode();
    return $code->save();
}

private function password()
{
    $inputKey = 'averyrandomandverylongstring';
    $this->_password = $inputKey;

    return $this->_password;
}

这是控制器样本

public function actionTest()
{
    $codes = new CodesSetup;
    return var_dump($codes->saveCodeSample());
}

这并没有给我任何错误,但问题是,所有数据都保存在数据库中,但加密数据除外。

模型规则:

public function rules()
{
    return [
        [['type', 'owner_id', 'code'], 'required'],
        [['owner_id', 'status', 'created_at', 'updated_at', 'author_id', 'updater_id'], 'integer'],
        [['type', 'code'], 'string', 'max' => 255]
    ];
}

2 个答案:

答案 0 :(得分:8)

保存前尝试utf8_encode,因数据库字段编码而发生问题。

$this->_encrypted = utf8_encode(Yii::$app->security->encryptByKey( $string, $inputKey ));

答案 1 :(得分:8)

我遇到了同样的问题,utf8_encode / utf8_decode为我工作

$encrypted = utf8_encode(Yii::$app->security->encryptByKey($data, $key));
$decrypted = Yii::$app->security->decryptByKey(utf8_decode($encrypted), $key);