crypter.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php namespace Laravel;
  2. if (trim(Config::$items['application']['key']) === '')
  3. {
  4. throw new \LogicException('The encryption class may not be used without an application key.');
  5. }
  6. class Crypter {
  7. /**
  8. * The encryption cipher.
  9. *
  10. * @var string
  11. */
  12. protected static $cipher = MCRYPT_RIJNDAEL_256;
  13. /**
  14. * The encryption mode.
  15. *
  16. * @var string
  17. */
  18. protected static $mode = MCRYPT_MODE_CBC;
  19. /**
  20. * Encrypt a string using Mcrypt.
  21. *
  22. * The given string will be encrypted using AES-256 encryption for a high
  23. * degree of security. The returned string will also be base64 encoded.
  24. *
  25. * Mcrypt must be installed on your machine before using this method, and
  26. * an application key must be specified in the application configuration.
  27. *
  28. * <code>
  29. * // Encrypt a string using the Mcrypt PHP extension
  30. * $encrypted = Crypter::encrpt('secret');
  31. * </code>
  32. *
  33. * @param string $value
  34. * @return string
  35. */
  36. public static function encrypt($value)
  37. {
  38. $iv = mcrypt_create_iv(static::iv_size(), MCRYPT_RAND);
  39. $value = mcrypt_encrypt(static::$cipher, static::key(), $value, static::$mode, $iv);
  40. return base64_encode($iv.$value);
  41. }
  42. /**
  43. * Decrypt a string using Mcrypt.
  44. *
  45. * The given encrypted value must have been encrypted using Laravel and
  46. * the application key specified in the application configuration file.
  47. *
  48. * Mcrypt must be installed on your machine before using this method.
  49. *
  50. * @param string $value
  51. * @return string
  52. */
  53. public static function decrypt($value)
  54. {
  55. if (($value = base64_decode($value)) === false)
  56. {
  57. throw new \InvalidArgumentException('Decryption error. Input value is not valid base64 data.');
  58. }
  59. $iv = substr($value, 0, static::iv_size());
  60. $value = substr($value, static::iv_size());
  61. return rtrim(mcrypt_decrypt(static::$cipher, static::key(), $value, static::$mode, $iv), "\0");
  62. }
  63. /**
  64. * Get the input vector size for the cipher and mode.
  65. *
  66. * @return int
  67. */
  68. protected static function iv_size()
  69. {
  70. return mcrypt_get_iv_size(static::$cipher, static::$mode);
  71. }
  72. /**
  73. * Get the encryption key from the application configuration.
  74. *
  75. * @return string
  76. */
  77. protected static function key()
  78. {
  79. return Config::$items['application']['key'];
  80. }
  81. }