Elgg
Version 6.1
Main Page
Related Pages
Namespaces
Classes
Files
Examples
File List
File Members
engine
classes
Elgg
Security
Crypto.php
Go to the documentation of this file.
1
<?php
2
3
namespace
Elgg\Security
;
4
5
use
Elgg\Exceptions\RangeException
;
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
}
substr
Elgg\Exceptions\RangeException
Exception thrown to indicate range errors during program execution.
Definition:
RangeException.php:13
Elgg\Security\Crypto
Cryptographic services.
Definition:
Crypto.php:12
$result
$result
Definition:
set_maintenance_mode.php:11
RangeException
rtrim
$length
if(!$item instanceof\ElggEntity) $length
Definition:
excerpt.php:16
ord
Elgg\Security\Crypto\CHARS_HEX
const CHARS_HEX
Character set for hexadecimal.
Definition:
Crypto.php:22
Elgg\Security
Definition:
Base64Url.php:3
Elgg\Security\Crypto\strlen
strlen($binary_string)
Count the number of bytes in a string.
Definition:
Crypto.php:126
Elgg\Security\Crypto\getRandomString
getRandomString($length, $chars=null)
Generate a random string of specified length.
Definition:
Crypto.php:43
Elgg\Security\Crypto\CHARS_PASSWORD
const CHARS_PASSWORD
Character set for temp passwords (no risk of embedded profanity/glyphs that look similar) ...
Definition:
Crypto.php:17
Elgg\Security\Crypto\areEqual
areEqual($str1, $str2)
Are two strings equal (compared in constant time)?
Definition:
Crypto.php:93
base64_encode
Generated on Wed Dec 4 2024 00:00:21 for Elgg by
1.8.11