crypter.php 2.0 KB

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