Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save an encrypted data using Yii::$app->security->encryptByKey() in Yii2

Tags:

php

yii

yii2

This is the model.

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

This is the controller sample

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

This doesn't give me any error but the PROBLEM is, all data is saved into the database except the encrypted one.

Model Rule:

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]
    ];
}
like image 350
adzadzadz Avatar asked Mar 22 '15 06:03

adzadzadz


2 Answers

I faced the same problem and utf8_encode/utf8_decode worked for me

$encrypted = utf8_encode(Yii::$app->security->encryptByKey($data, $key));
$decrypted = Yii::$app->security->decryptByKey(utf8_decode($encrypted), $key);
like image 107
leealex Avatar answered Nov 02 '22 19:11

leealex


Try utf8_encode before saving, issue occurs because of database fields encoding.

$this->_encrypted = utf8_encode(Yii::$app->security->encryptByKey( $string, $inputKey ));
like image 45
Lesser Avatar answered Nov 02 '22 18:11

Lesser