I am saving the encrypted user data (including user email which is used to login) with Laravel's built in encryption method.
At login, I have to provide encrypted email for authentication but Encryption algorithm generates a different string each time against the same string.
I'm using the following trait for saving encrypted data.
How can I overcome this please?
namespace App\Traits;
use Illuminate\Support\Facades\Crypt;
/**
* Class Encryptable
* @package App\Traits
*/
trait Encryptable
{
/**
* If the attribute is in the encryptable array
* then decrypt it.
*
* @param $key
*
* @return $value
*/
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable) && $value !== '')
$value = Crypt::decrypt($value);
return $value;
}
/**
* If the attribute is in the encryptable array
* then encrypt it.
*
* @param $key
*
* @return $value
*/
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable))
$value = Crypt::encrypt($value);
return parent::setAttribute($key, $value);
}
/**
* When need to make sure that we iterate through
* all the keys.
*
* @return array
*/
public function attributesToArray()
{
$attributes = parent::attributesToArray();
foreach ($this->encryptable as $key)
{
if (isset($attributes[$key]))
$attributes[$key] = Crypt::decrypt($attributes[$key]);
}
return $attributes;
}
}
Usage in User model
namespace App;
use App\Traits\Encryptable;
class User extends Authenticatable implements MustVerifyEmail
{
use Encryptable;
protected $encryptable = [
'first_name',
'sur_name',
'email',
'mobile',
];
}
You don't. Encrypted payload must be different each time, even if the same plaintext is encrypted. Laravel does it properly.
Reason for this behavior is to protect against cracking the algorithm and secret used for encrypting. If the same payload yields exactly the same ciphertext, it becomes by order of magnitude easier to crack it.
What you're asking for is not even going to solve your problem. Solution to your problem isn't changing the encryption scheme, it's something entirely different. Consider deleting this question and ask about your actual problem and not your attempted solution.