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

How can I save an encrypted data using Yii::$app->security->encryptByKey() in 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]
    ];
}

在保存之前尝试utf8_encode,由于数据库字段编码而出现问题。

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

我遇到了同样的问题,utf8_encode/utf8_decode 对我有用

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