Elgg  Version master
SiteSecret.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
8 
24 class SiteSecret {
25 
26  const CONFIG_KEY = '__site_secret__';
27 
28  protected string $key;
29 
36  public function __construct(protected Crypto $crypto, protected ConfigTable $table) {
37  $key = $table->get(self::CONFIG_KEY);
38  if (!$key) {
39  throw new InstallationException('Site secret is not in the config table.');
40  }
41 
42  $this->key = $key;
43  }
44 
55  public function get($raw = false) {
56  if (!$this->key) {
57  throw new RuntimeException('Secret key is not set');
58  }
59 
60  if (!$raw) {
61  return $this->key;
62  }
63 
64  // try to return binary key
65  if ($this->key[0] === 'z') {
66  // new keys are "z" + base64URL
67  $base64 = strtr(substr($this->key, 1), '-_', '+/');
68  $key = base64_decode($base64);
69  if ($key !== false) {
70  return $key;
71  }
72 
73  // on failure, at least return string key :/
74  return $this->key;
75  }
76 
77  // old keys are hex
78  return hex2bin($this->key);
79  }
80 
89  public function getStrength() {
90  $secret = $this->get();
91  if ($secret[0] !== 'z') {
92  $rand_max = getrandmax();
93  if ($rand_max < pow(2, 16)) {
94  return 'weak';
95  }
96 
97  if ($rand_max < pow(2, 32)) {
98  return 'moderate';
99  }
100  }
101 
102  return 'strong';
103  }
104 
113  public function regenerate() {
114  $key = 'z' . $this->crypto->getRandomString(31);
115 
116  $this->table->set(self::CONFIG_KEY, $key);
117  }
118 }
Manages a site-specific secret key, encoded as a 32 byte string "secret".
Definition: SiteSecret.php:24
regenerate()
Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL) and save to...
Definition: SiteSecret.php:113
Cryptographic services.
Definition: Crypto.php:12
Exception thrown if an error which can only be found on runtime occurs.
get(string $name)
Gets a configuration value.
Updates the basic settings for the primary site object.
__construct(protected Crypto $crypto, protected ConfigTable $table)
Constructor.
Definition: SiteSecret.php:36
Thrown when there is a major problem with the installation.
$table
Definition: user.php:37
getStrength()
Get the strength of the site secret.
Definition: SiteSecret.php:89
Manipulates values in the dbprefix_config table.
Definition: ConfigTable.php:16