Skip to content

Instantly share code, notes, and snippets.

@lukepolo
Created May 8, 2015 18:16
Show Gist options
  • Save lukepolo/2417bc94ab2b35ae9e33 to your computer and use it in GitHub Desktop.
Save lukepolo/2417bc94ab2b35ae9e33 to your computer and use it in GitHub Desktop.
Laravel Encryptor
<?php namespace App\Services;
use Exception;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
class Encrypter implements EncrypterContract {
/**
* The encryption key.
*
* @var string
*/
protected $key;
/**
* The algorithm used for encryption.
*
* @var string
*/
protected $cipher = MCRYPT_RIJNDAEL_256;
/**
* The mode used for encryption.
*
* @var string
*/
protected $mode = MCRYPT_MODE_ECB;
/**
* Create a new encrypter instance.
*
* @param string $key
*/
public function __construct($key)
{
$this->key = (string) $key;
}
/**
* Encrypt the given value.
*
* @param string $value
* @return string
*/
public function encrypt($value)
{
return base64_encode(mcrypt_encrypt($this->cipher, $this->key, $value, $this->mode, $this->generate_iv()));
}
public function generate_iv()
{
return mcrypt_create_iv($this->getIvSize(), $this->getRandomizer());
}
/**
* Decrypt the given value.
*
* @param string $hash
* @return string
*/
public function decrypt($hash)
{
try
{
return mcrypt_decrypt($this->cipher, $this->key, base64_decode($hash), $this->mode, $this->generate_iv());
}
catch (Exception $e)
{
throw new DecryptException($e->getMessage());
}
}
/**
* Get the IV size for the cipher.
*
* @return int
*/
protected function getIvSize()
{
return mcrypt_get_iv_size($this->cipher, $this->mode);
}
/**
* Get the random data source available for the OS.
*
* @return int
*/
protected function getRandomizer()
{
return MCRYPT_RAND;
}
/**
* Set the encryption key.
*
* @param string $key
* @return void
*/
public function setKey($key)
{
$this->key = (string) $key;
}
/**
* Set the encryption cipher.
*
* @param string $cipher
* @return void
*/
public function setCipher($cipher)
{
$this->cipher = $cipher;
}
/**
* Set the encryption mode.
*
* @param string $mode
* @return void
*/
public function setMode($mode)
{
$this->mode = $mode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment