crypter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php namespace Laravel; defined('DS') or die('No direct script access.');
  2. class Crypter {
  3. /**
  4. * The encryption cipher.
  5. *
  6. * @var string
  7. */
  8. public static $cipher = MCRYPT_RIJNDAEL_256;
  9. /**
  10. * The encryption mode.
  11. *
  12. * @var string
  13. */
  14. public static $mode = MCRYPT_MODE_CBC;
  15. /**
  16. * Encrypt a string using Mcrypt.
  17. *
  18. * The string will be encrypted using the AES-256 scheme and will be base64 encoded.
  19. *
  20. * @param string $value
  21. * @return string
  22. */
  23. public static function encrypt($value)
  24. {
  25. $iv = mcrypt_create_iv(static::iv_size(), MCRYPT_RAND);
  26. $value = mcrypt_encrypt(static::$cipher, static::key(), $value, static::$mode, $iv);
  27. return base64_encode($iv.$value);
  28. }
  29. /**
  30. * Decrypt a string using Mcrypt.
  31. *
  32. * @param string $value
  33. * @return string
  34. */
  35. public static function decrypt($value)
  36. {
  37. $value = base64_decode($value);
  38. // To decrypt the value, we first need to extract the input vector and
  39. // the encrypted value. The input vector size varies across different
  40. // encryption ciphers and modes, so we will get the correct size for
  41. // the cipher and mode being used by the class.
  42. $iv = substr($value, 0, static::iv_size());
  43. $value = substr($value, static::iv_size());
  44. // Once we have the input vector and the value, we can give them both
  45. // to Mcrypt for decryption. The value is sometimes padded with \0,
  46. // so we will trim all of the padding characters from the string.
  47. $key = static::key();
  48. return rtrim(mcrypt_decrypt(static::$cipher, $key, $value, static::$mode, $iv), "\0");
  49. }
  50. /**
  51. * Get the input vector size for the cipher and mode.
  52. *
  53. * @return int
  54. */
  55. protected static function iv_size()
  56. {
  57. return mcrypt_get_iv_size(static::$cipher, static::$mode);
  58. }
  59. /**
  60. * Get the encryption key from the application configuration.
  61. *
  62. * @return string
  63. */
  64. protected static function key()
  65. {
  66. return Config::get('application.key');
  67. }
  68. }