summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/PrivateKey.php
blob: 2ff9cf2ca87d373e382980fb9f13ba367b223587 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php

namespace Drupal\Core;

use Drupal\Core\State\StateInterface;
use Drupal\Component\Utility\Crypt;

/**
 * Manages the Drupal private key.
 */
class PrivateKey {

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Constructs the private key object.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * Gets the private key.
   *
   * @return string
   *   The private key.
   */
  public function get() {
    if (!$key = $this->state->get('system.private_key')) {
      $key = $this->create();
      $this->set($key);
    }

    return $key;
  }

  /**
   * Sets the private key.
   *
   * @param string $key
   *   The private key to set.
   */
  public function set(#[\SensitiveParameter] $key) {
    return $this->state->set('system.private_key', $key);
  }

  /**
   * Creates a new private key.
   *
   * @return string
   *   The private key.
   */
  protected function create() {
    return Crypt::randomBytesBase64(55);
  }

}