Elgg  Version 5.1
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 
31  private $key;
32 
36  protected $crypto;
37 
41  protected $table;
42 
50  $this->crypto = $crypto;
51  $this->table = $table;
52 
53  $key = $table->get(self::CONFIG_KEY);
54  if (!$key) {
55  throw new InstallationException('Site secret is not in the config table.');
56  }
57 
58  $this->key = $key;
59  }
60 
71  public function get($raw = false) {
72  if (!$this->key) {
73  throw new RuntimeException('Secret key is not set');
74  }
75 
76  if (!$raw) {
77  return $this->key;
78  }
79 
80  // try to return binary key
81  if ($this->key[0] === 'z') {
82  // new keys are "z" + base64URL
83  $base64 = strtr(substr($this->key, 1), '-_', '+/');
84  $key = base64_decode($base64);
85  if ($key !== false) {
86  return $key;
87  }
88 
89  // on failure, at least return string key :/
90  return $this->key;
91  }
92 
93  // old keys are hex
94  return hex2bin($this->key);
95  }
96 
105  public function getStrength() {
106  $secret = $this->get();
107  if ($secret[0] !== 'z') {
108  $rand_max = getrandmax();
109  if ($rand_max < pow(2, 16)) {
110  return 'weak';
111  }
112 
113  if ($rand_max < pow(2, 32)) {
114  return 'moderate';
115  }
116  }
117 
118  return 'strong';
119  }
120 
129  public function regenerate() {
130  $key = 'z' . $this->crypto->getRandomString(31);
131 
132  $this->table->set(self::CONFIG_KEY, $key);
133  }
134 }
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:129
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.
Thrown when there is a major problem with the installation.
__construct(Crypto $crypto, ConfigTable $table)
Constructor.
Definition: SiteSecret.php:49
getStrength()
Get the strength of the site secret.
Definition: SiteSecret.php:105
Manipulates values in the dbprefix_config table.
Definition: ConfigTable.php:16