2015-11-21 14:27:53 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Gist\Service;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
|
|
|
|
/**
|
2016-11-13 00:44:23 +01:00
|
|
|
* Class SaltGenerator.
|
|
|
|
*
|
2015-11-21 14:27:53 +01:00
|
|
|
* @author Simon Vieille <simon@deblan.fr>
|
|
|
|
*/
|
|
|
|
class SaltGenerator
|
|
|
|
{
|
2016-11-13 00:44:23 +01:00
|
|
|
/**
|
|
|
|
* Generates a random salt.
|
|
|
|
*
|
|
|
|
* @param int $length
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
2017-06-25 19:13:27 +02:00
|
|
|
public function generate($length = 32, $isApiKey = false)
|
2015-11-21 14:27:53 +01:00
|
|
|
{
|
|
|
|
if (!is_numeric($length)) {
|
|
|
|
throw new InvalidArgumentException('Paramter length must be a valid integer.');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (function_exists('openssl_random_pseudo_bytes')) {
|
2017-06-25 19:13:27 +02:00
|
|
|
$string = base64_encode(openssl_random_pseudo_bytes(256));
|
2015-11-21 14:27:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (function_exists('mcrypt_create_iv')) {
|
2017-06-25 19:13:27 +02:00
|
|
|
$string = base64_encode(mcrypt_create_iv(256, MCRYPT_DEV_URANDOM));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!empty($string)) {
|
|
|
|
if (true === $isApiKey) {
|
|
|
|
$string = str_replace(
|
|
|
|
array('+', '%', '/', '#', '&'),
|
|
|
|
'',
|
|
|
|
$string
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return substr($string, 0, $length);
|
2015-11-21 14:27:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new RuntimeException('You must enable openssl or mcrypt modules.');
|
|
|
|
}
|
|
|
|
}
|