crypter.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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'll get the correct size.
  41. $iv = substr($value, 0, static::iv_size());
  42. $value = substr($value, static::iv_size());
  43. // Once we have the input vector and the value, we can give them both
  44. // to Mcrypt for decryption. The value is sometimes padded with \0,
  45. // so we will trim all of the padding characters.
  46. $key = static::key();
  47. return rtrim(mcrypt_decrypt(static::$cipher, $key, $value, static::$mode, $iv), "\0");
  48. }
  49. /**
  50. * Get the input vector size for the cipher and mode.
  51. *
  52. * @return int
  53. */
  54. protected static function iv_size()
  55. {
  56. return mcrypt_get_iv_size(static::$cipher, static::$mode);
  57. }
  58. /**
  59. * Get the encryption key from the application configuration.
  60. *
  61. * @return string
  62. */
  63. protected static function key()
  64. {
  65. return Config::get('application.key');
  66. }
  67. }