Elgg  Version 2.3
SiteSecret.php
Go to the documentation of this file.
1 <?php
2 namespace Elgg\Database;
3 
22 class SiteSecret {
23 
27  private $datalist;
28 
34  public function __construct(Datalist $datalist) {
35  $this->datalist = $datalist;
36  }
37 
41  private $test_secret = '';
42 
49  public function setTestingSecret($secret) {
50  $this->test_secret = $secret;
51  }
52 
63  function init() {
64  $secret = 'z' . _elgg_services()->crypto->getRandomString(31);
65 
66  if ($this->datalist->set('__site_secret__', $secret)) {
67  return $secret;
68  }
69 
70  return false;
71  }
72 
83  function get($raw = false) {
84  if ($this->test_secret) {
85  $secret = $this->test_secret;
86  } else {
87  $secret = $this->datalist->get('__site_secret__');
88  }
89  if (!$secret) {
90  $secret = $this->init();
91  }
92 
93  if ($raw) {
94  // try to return binary key
95  if ($secret[0] === 'z') {
96  // new keys are "z" + base64URL
97  $base64 = strtr(substr($secret, 1), '-_', '+/');
98  $key = base64_decode($base64);
99  if ($key !== false) {
100  // on failure, at least return string key :/
101  return $key;
102  }
103  } else {
104  // old keys are hex
105  return hex2bin($secret);
106  }
107  }
108 
109  return $secret;
110  }
111 
121  function getStrength() {
122  $secret = $this->get();
123  if ($secret[0] !== 'z') {
124  $rand_max = getrandmax();
125  if ($rand_max < pow(2, 16)) {
126  return 'weak';
127  }
128  if ($rand_max < pow(2, 32)) {
129  return 'moderate';
130  }
131  }
132  return 'strong';
133  }
134 }
__construct(Datalist $datalist)
Constructor.
Definition: SiteSecret.php:34
setTestingSecret($secret)
Set a secret to be used in testing.
Definition: SiteSecret.php:49
init()
Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL)...
Definition: SiteSecret.php:63
getStrength()
Get the strength of the site secret.
Definition: SiteSecret.php:121
$key
Definition: summary.php:34
_elgg_services(\Elgg\Di\ServiceProvider $services=null)
Get the global service provider.
Definition: autoloader.php:17