-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Hotfixing permission helper issue Adding a crypto helper. Improving permissions helper.
1 parent
bd866ab
commit 9313bfe
Showing
3 changed files
with
88 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
<?php | ||
/** | ||
* Created by PhpStorm. | ||
* User: gustavs | ||
* Date: 18.14.2 | ||
* Time: 13:37 | ||
*/ | ||
|
||
namespace Solspace\Commons\Helpers; | ||
|
||
class CryptoHelper | ||
{ | ||
/** | ||
* Generate a unique token | ||
* | ||
* @param int $length | ||
* | ||
* @return string | ||
*/ | ||
public static function getUniqueToken(int $length = 40): string | ||
{ | ||
$token = ''; | ||
$codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | ||
$codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz'; | ||
$codeAlphabet .= '0123456789'; | ||
$max = strlen($codeAlphabet); // edited | ||
|
||
for ($i = 0; $i < $length; $i++) { | ||
$token .= $codeAlphabet[self::getSecureRandomInt(0, $max - 1)]; | ||
} | ||
|
||
return $token; | ||
} | ||
|
||
/** | ||
* Generate a secure random int | ||
* | ||
* @param int $min | ||
* @param int $max | ||
* | ||
* @return int | ||
*/ | ||
public static function getSecureRandomInt(int $min, int $max): int | ||
{ | ||
if (function_exists('random_int')) { | ||
return random_int($min, $max); | ||
} | ||
|
||
$range = $max - $min; | ||
|
||
if ($range < 1) { | ||
return $min; // not so random... | ||
} | ||
|
||
$log = ceil(log($range, 2)); | ||
$bytes = (int) ($log / 8) + 1; // length in bytes | ||
$bits = (int) $log + 1; // length in bits | ||
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1 | ||
do { | ||
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); | ||
$rnd = $rnd & $filter; // discard irrelevant bits | ||
} while ($rnd > $range); | ||
|
||
return $min + $rnd; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters