Elgg  Version 3.0
ElggCrypto.php
Go to the documentation of this file.
1 <?php
2 
8 class ElggCrypto {
9 
13  const CHARS_PASSWORD = 'bcdfghjklmnpqrstvwxyz2346789';
14 
18  const CHARS_HEX = '0123456789abcdef';
19 
39  public function getRandomString($length, $chars = null) {
40  if ($length < 1) {
41  throw new \InvalidArgumentException('Length should be >= 1');
42  }
43 
44  if (empty($chars)) {
45  $numBytes = ceil($length * 0.75);
46  $bytes = random_bytes($numBytes);
47  $string = substr(rtrim(base64_encode($bytes), '='), 0, $length);
48 
49  // Base64 URL
50  return strtr($string, '+/', '-_');
51  }
52 
53  if ($chars == self::CHARS_HEX) {
54  // hex is easy
55  $bytes = random_bytes(ceil($length / 2));
56  return substr(bin2hex($bytes), 0, $length);
57  }
58 
59  $listLen = strlen($chars);
60 
61  if ($listLen == 1) {
62  return str_repeat($chars, $length);
63  }
64 
65  $bytes = random_bytes($length);
66  $pos = 0;
67  $result = '';
68  for ($i = 0; $i < $length; $i++) {
69  $pos = ($pos + ord($bytes[$i])) % $listLen;
70  $result .= $chars[$pos];
71  }
72 
73  return $result;
74  }
75 
89  public function areEqual($str1, $str2) {
90  $len1 = $this->strlen($str1);
91  $len2 = $this->strlen($str2);
92  if ($len1 !== $len2) {
93  return false;
94  }
95 
96  $status = 0;
97  for ($i = 0; $i < $len1; $i++) {
98  $status |= (ord($str1[$i]) ^ ord($str2[$i]));
99  }
100 
101  return $status === 0;
102  }
103 
122  protected function strlen($binary_string) {
123  if (function_exists('mb_strlen')) {
124  return mb_strlen($binary_string, '8bit');
125  }
126  return strlen($binary_string);
127  }
128 }
areEqual($str1, $str2)
Are two strings equal (compared in constant time)?
Definition: ElggCrypto.php:89
const CHARS_PASSWORD
Character set for temp passwords (no risk of embedded profanity/glyphs that look similar) ...
Definition: ElggCrypto.php:13
if(!$item instanceof ElggEntity) $length
Definition: excerpt.php:16
const CHARS_HEX
Character set for hexadecimal.
Definition: ElggCrypto.php:18
getRandomString($length, $chars=null)
Generate a random string of specified length.
Definition: ElggCrypto.php:39
strlen($binary_string)
Count the number of bytes in a string.
Definition: ElggCrypto.php:122