gist/src/Gist/Service/SaltGenerator.php

50 lines
1.1 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Gist\Service;
use InvalidArgumentException;
/**
2016-11-13 00:44:23 +01:00
* Class SaltGenerator.
*
* @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)
{
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));
}
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);
}
throw new RuntimeException('You must enable openssl or mcrypt modules.');
}
}