crypter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php namespace Laravel\Security;
  2. class Crypter {
  3. /**
  4. * The encryption cipher.
  5. *
  6. * @var string
  7. */
  8. public $cipher;
  9. /**
  10. * The encryption mode.
  11. *
  12. * @var string
  13. */
  14. public $mode;
  15. /**
  16. * The encryption key.
  17. *
  18. * @var string
  19. */
  20. public $key;
  21. /**
  22. * Create a new Crypter instance.
  23. *
  24. * @param string $cipher
  25. * @param string $mode
  26. * @param string $key
  27. * @return void
  28. */
  29. public function __construct($cipher, $mode, $key)
  30. {
  31. $this->cipher = $cipher;
  32. $this->mode = $mode;
  33. $this->key = $key;
  34. if (trim((string) $this->key) === '')
  35. {
  36. throw new \Exception('The encryption class may not be used without an encryption key.');
  37. }
  38. }
  39. /**
  40. * Encrypt a string using Mcrypt.
  41. *
  42. * @param string $value
  43. * @return string
  44. */
  45. public function encrypt($value)
  46. {
  47. $iv = mcrypt_create_iv($this->iv_size(), $this->randomizer());
  48. return base64_encode($iv.mcrypt_encrypt($this->cipher, $this->key, $value, $this->mode, $iv));
  49. }
  50. /**
  51. * Get the random number source available to the OS.
  52. *
  53. * @return int
  54. */
  55. protected function randomizer()
  56. {
  57. if (defined('MCRYPT_DEV_URANDOM'))
  58. {
  59. return MCRYPT_DEV_URANDOM;
  60. }
  61. elseif (defined('MCRYPT_DEV_RANDOM'))
  62. {
  63. return MCRYPT_DEV_RANDOM;
  64. }
  65. return MCRYPT_RAND;
  66. }
  67. /**
  68. * Decrypt a string using Mcrypt.
  69. *
  70. * @param string $value
  71. * @return string
  72. */
  73. public function decrypt($value)
  74. {
  75. if ( ! is_string($value = base64_decode($value, true)))
  76. {
  77. throw new \Exception('Decryption error. Input value is not valid base64 data.');
  78. }
  79. list($iv, $value) = array(substr($value, 0, $this->iv_size()), substr($value, $this->iv_size()));
  80. return rtrim(mcrypt_decrypt($this->cipher, $this->key, $value, $this->mode, $iv), "\0");
  81. }
  82. /**
  83. * Get the input vector size for the cipher and mode.
  84. *
  85. * Different ciphers and modes use varying lengths of input vectors.
  86. *
  87. * @return int
  88. */
  89. private function iv_size()
  90. {
  91. return mcrypt_get_iv_size($this->cipher, $this->mode);
  92. }
  93. }