Closed ali-ichk closed 6 months ago
Suggested implementation: getSalt3
Implementations:
/**
* Original getSalt() in Gibbons
*/
function getSalt1() {
$c = explode(' ', '. / a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z 0 1 2 3 4 5 6 7 8 9');
$ks = array_rand($c, 22);
$s = '';
foreach ($ks as $k) {
$s .= $c[$k];
}
return $s;
}
/**
* A fixed version of the proposed getSalt() implementation in this PR.
*/
function getSalt2() {
$c = explode(' ', '. / a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z 0 1 2 3 4 5 6 7 8 9');
$ks = [];
for ($x = 0; $x < 22; $x++) {
$ind = mt_rand(0, count($c) - 1);
$ks[] = $c[$ind];
}
$s = '';
foreach ($ks as $k) {
$s .= $k;
}
return $s;
}
/**
* A simplified version of getSalt2() provides better performance.
*/
function getSalt3() {
$c = './aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789';
$s = '';
$l = strlen($c);
for ($x = 0; $x < 22; $x++) {
$ind = mt_rand(0, $l - 1);
$s .= $c[$ind];
}
return $s;
}
Benchmark:
// Benchmarking the callback
function bench(string $name, Callable $cb, int $scale) {
$start = microtime(true);
echo "Benchmarking: $name\n";
for ($i=0; $i<$scale; $i++) {
$cb();
}
echo "time used: " . sprintf("%.5f", (microtime(true) - $start)) . "s\n\n";
}
$scale = 500000;
bench('getSalt1()', getSalt1(...), $scale);
bench('getSalt2()', getSalt2(...), $scale);
bench('getSalt3()', getSalt3(...), $scale);
Results:
Benchmarking: getSalt1()
time used: 0.82821s
Benchmarking: getSalt2()
time used: 0.96580s
Benchmarking: getSalt3()
time used: 0.53052s
Outputs comparison (each run for 10 times):
getSalt1(): AbCeEGhHIlLMNPQtxXz012
getSalt1(): ./aABcDFghIKosuVwWx239
getSalt1(): BdDFgiJPqQRtUwxyYz2358
getSalt1(): /abcEfiIKlmMPQtTXyY036
getSalt1(): /bFgGjJlmMQUvVwWy12569
getSalt1(): ABeEFgHIjlLoPrRTUx0236
getSalt1(): .bBEfFHjkLPrvVxXYZ2569
getSalt1(): BcDEhHiImNPqruwyY06789
getSalt1(): aCdfFhikKMorRTuwWyz156
getSalt1(): aCDghIjmnoORstuvWx0246
getSalt2(): jUBTOqWBViKeKAICMJjnD7
getSalt2(): pu6JqHv6RBZc.0GLy8Zbcf
getSalt2(): G6clQF3bNLpm0VMZ98CqF4
getSalt2(): tQU2q0Iwfp4i5PqxNtWgP8
getSalt2(): 9sagx5Hd6mC5sSxaBz5cZD
getSalt2(): Ehi5qhDHj8DQHlr4EnqzGM
getSalt2(): kUNrIeKIsxNhmUeOlad24S
getSalt2(): zFHIHbijWiYZC/nc23wS58
getSalt2(): iS9DzCHFMqsu18XW8SToML
getSalt2(): OKUiCvQrdIw2haADebR4oC
getSalt3(): ZuTa0eEJ/.MNYOZSb4szp/
getSalt3(): .MuFfRUGZDiAbv8X.6NpKR
getSalt3(): 3EfMbZKpYHFBVWTIcL6i.X
getSalt3(): jlMZkbOSxUHwqa3IGm3bMI
getSalt3(): XnK3xuVCnVfI2iUj35Crlw
getSalt3(): 6YFV1cWXQCJW7ScQls/XUP
getSalt3(): wwlI8t.ljRLLT6KAsp3mZx
getSalt3(): AW6ctsr.NR/5BQfwTcgjTz
getSalt3(): bBvQLHegIok/lLLZfXOeQ.
getSalt3(): ERbKmyZqMkNDbwvuKAosWB
Description Fixed the bug in the function.php file by updating the getSalt() function s that it uses the mt_rand() function to help generate a random string. Also, applied auto indentation to make the lines of code look cleaner and nicer.