PrivateKey.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Drupal\Core;
  3. use Drupal\Core\State\StateInterface;
  4. use Drupal\Component\Utility\Crypt;
  5. /**
  6. * Manages the Drupal private key.
  7. */
  8. class PrivateKey {
  9. /**
  10. * The state service.
  11. *
  12. * @var \Drupal\Core\State\StateInterface
  13. */
  14. protected $state;
  15. /**
  16. * Constructs the token generator.
  17. *
  18. * @param \Drupal\Core\State\StateInterface $state
  19. * The state service.
  20. */
  21. public function __construct(StateInterface $state) {
  22. $this->state = $state;
  23. }
  24. /**
  25. * Gets the private key.
  26. *
  27. * @return string
  28. * The private key.
  29. */
  30. public function get() {
  31. if (!$key = $this->state->get('system.private_key')) {
  32. $key = $this->create();
  33. $this->set($key);
  34. }
  35. return $key;
  36. }
  37. /**
  38. * Sets the private key.
  39. *
  40. * @param string $key
  41. * The private key to set.
  42. */
  43. public function set($key) {
  44. return $this->state->set('system.private_key', $key);
  45. }
  46. /**
  47. * Creates a new private key.
  48. *
  49. * @return string
  50. * The private key.
  51. */
  52. protected function create() {
  53. return Crypt::randomBytesBase64(55);
  54. }
  55. }