Skip to content

Instantly share code, notes, and snippets.

@uno-de-piera
Last active May 23, 2018 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uno-de-piera/5bf4ae0775dbb9065ca046932a081e55 to your computer and use it in GitHub Desktop.
Save uno-de-piera/5bf4ae0775dbb9065ca046932a081e55 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
/**
* Trait Encryptable
* @package App\Traits
*/
trait Encryptable
{
/**
* @return mixed
*/
public function getSecretKey () {
return env('APP_DB_KEY');
}
/**
* @return mixed
*/
public function getKeyInitVector () {
return env('APP_KEY');
}
/**
* @return \Illuminate\Config\Repository|mixed
*/
public function getEncryptMethod () {
return config('app.cipher');
}
/**
* @param $string
* @return bool|string
*/
public function encrypt( $string ) {
$key = hash( config('app.encryption'), $this->getSecretKey() );
$iv = substr( hash( config('app.encryption'), $this->getKeyInitVector() ), 0, 16 );
return base64_encode( openssl_encrypt( $string, $this->getEncryptMethod(), $key, 0, $iv ) );
}
/**
* @param $string
* @return bool|string
*/
public function decrypt( $string ) {
$key = hash( config('app.encryption'), $this->getSecretKey() );
$iv = substr( hash( config('app.encryption'), $this->getKeyInitVector() ), 0, 16 );
return openssl_decrypt( base64_decode( $string ), $this->getEncryptMethod(), $key, 0, $iv );
}
/**
* @param $key
* @return bool|string
*/
public function getAttribute($key)
{
if (in_array($key, $this->encryptable)) {
$value = $this->decrypt($value);
return $value;
}
return parent::getAttribute($key);
}
/**
* @param $key
* @param $value
* @return mixed
*/
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = $this->encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment