Elgg  Version master
Crypto.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
6 
12 class Crypto {
13 
17  const CHARS_PASSWORD = 'bcdfghjklmnpqrstvwxyz2346789';
18 
22  const CHARS_HEX = '0123456789abcdef';
23 
43  public function getRandomString($length, $chars = null) {
44  if ($length < 1) {
45  throw new RangeException('Length should be >= 1');
46  }
47 
48  if (empty($chars)) {
49  $numBytes = ceil($length * 0.75);
50  $bytes = random_bytes($numBytes);
51  $string = substr(rtrim(base64_encode($bytes), '='), 0, $length);
52 
53  // Base64 URL
54  return strtr($string, '+/', '-_');
55  }
56 
57  if ($chars == self::CHARS_HEX) {
58  // hex is easy
59  $bytes = random_bytes(ceil($length / 2));
60  return substr(bin2hex($bytes), 0, $length);
61  }
62 
63  $listLen = strlen($chars);
64 
65  if ($listLen == 1) {
66  return str_repeat($chars, $length);
67  }
68 
69  $bytes = random_bytes($length);
70  $pos = 0;
71  $result = '';
72  for ($i = 0; $i < $length; $i++) {
73  $pos = ($pos + ord($bytes[$i])) % $listLen;
74  $result .= $chars[$pos];
75  }
76 
77  return $result;
78  }
79 
93  public function areEqual($str1, $str2) {
94  $len1 = $this->strlen($str1);
95  $len2 = $this->strlen($str2);
96  if ($len1 !== $len2) {
97  return false;
98  }
99 
100  $status = 0;
101  for ($i = 0; $i < $len1; $i++) {
102  $status |= (ord($str1[$i]) ^ ord($str2[$i]));
103  }
104 
105  return $status === 0;
106  }
107 
126  protected function strlen($binary_string) {
127  if (function_exists('mb_strlen')) {
128  return mb_strlen($binary_string, '8bit');
129  }
130 
131  return strlen($binary_string);
132  }
133 }
Exception thrown to indicate range errors during program execution.
Cryptographic services.
Definition: Crypto.php:12
if(!$item instanceof\ElggEntity) $length
Definition: excerpt.php:16
const CHARS_HEX
Character set for hexadecimal.
Definition: Crypto.php:22
strlen($binary_string)
Count the number of bytes in a string.
Definition: Crypto.php:126
getRandomString($length, $chars=null)
Generate a random string of specified length.
Definition: Crypto.php:43
const CHARS_PASSWORD
Character set for temp passwords (no risk of embedded profanity/glyphs that look similar) ...
Definition: Crypto.php:17
areEqual($str1, $str2)
Are two strings equal (compared in constant time)?
Definition: Crypto.php:93