/** * A Monte Carlo test that generates $cycles numbers from 0 to $tot * and test if the numbers are above or below the line y=x with a * frequency range of [$min, $max] * * Note: this code is inspired by the random number generator test * included in the PHP-CryptLib project of Anthony Ferrara * @see https://github.com/ircmaxell/PHP-CryptLib * * @dataProvider provideRandInt */ public function testRandInteger($num, $valid, $cycles, $tot, $min, $max, $strong) { try { $test = Rand::getBytes(1, $strong); } catch (\Zend\Math\Exception\RuntimeException $e) { $this->markTestSkipped($e->getMessage()); } $i = 0; $count = 0; do { $up = 0; $down = 0; for ($i = 0; $i < $cycles; $i++) { $x = Rand::getInteger(0, $tot, $strong); $y = Rand::getInteger(0, $tot, $strong); if ($x > $y) { $up++; } elseif ($x < $y) { $down++; } } $this->assertGreaterThan(0, $up); $this->assertGreaterThan(0, $down); $ratio = $up / $down; if ($ratio > $min && $ratio < $max) { $count++; } $i++; } while ($i < $num && $count < $valid); if ($count < $valid) { $this->fail('The random number generator failed the Monte Carlo test'); } }
public function export() { $path = __DIR__ . '/../../../../../../public/xls/'; if (!is_dir($path)) { throw new \Exception("Please make sure that 'public/xls' directory exists"); } $fileName = str_replace("/", ".", base64_encode(Rand::getBytes(6, true)) . '_' . date("Y-m-d-H:i:s") . '.xls'); $file = fopen($path . $fileName, "w"); $count = 0; $html = null; $html .= "<table>"; $html .= "<tr>"; foreach ($this->headers as $headers) { $html .= "<th>{$headers}</th>"; } $html .= "</tr>"; foreach ($this->resultFormatedData as $data) { foreach ($data as $colunas) { $count++; if ($count == 0) { $html .= "<tr>"; } $html .= "<td>{$colunas}</td>"; if ($count == count($this->headers)) { $html .= "</tr>"; $count = 0; } } } fputs($file, utf8_decode($html)); fclose($file); return '/xls/' . $fileName; }
/** * Bcrypt * * @param string $password * @throws Exception\RuntimeException * @return string */ public function create($password) { if (empty($this->salt)) { $salt = Rand::getBytes(self::MIN_SALT_SIZE); } else { $salt = $this->salt; } $salt64 = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); /** * Check for security flaw in the bcrypt implementation used by crypt() * @see http://php.net/security/crypt_blowfish.php */ if (PHP_VERSION_ID >= 50307 && !$this->backwardCompatibility) { $prefix = '$2y$'; } else { $prefix = '$2a$'; // check if the password contains 8-bit character if (preg_match('/[\\x80-\\xFF]/', $password)) { throw new Exception\RuntimeException('The bcrypt implementation used by PHP can contain a security flaw ' . 'using password with 8-bit character. ' . 'We suggest to upgrade to PHP 5.3.7+ or use passwords with only 7-bit characters'); } } $hash = crypt($password, $prefix . $this->cost . '$' . $salt64); if (strlen($hash) < 13) { throw new Exception\RuntimeException('Error during the bcrypt generation'); } return $hash; }
/** * Get the base name of the persistently stored file. * * @return string */ public function getStorageBaseName() { if (isset($this->storageBaseName)) { return $this->storageBaseName; } $this->storageBaseName = bin2hex(Rand::getBytes(20)); return $this->storageBaseName; }
public function __construct(array $options = array()) { (new Hydrator\ClassMethods())->hydrate($options, $this); $this->created = new \DateTime("now"); $this->modified = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activekey = md5($this->email . $this->salt); }
/** * @param array $options */ public function __construct(array $options = []) { (new Hydrator\ClassMethods())->hydrate($options, $this); $this->updatedAt = new \DateTime('now'); $this->createdAt = new \DateTime('now'); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
public function create($password) { if (empty($this->salt)) { $salt = $this->salt = Rand::getBytes(self::MIN_SALT_SIZE); } else { $salt = $this->salt; } return parent::create($password); }
/** * Bcrypt * * @param string $password * @throws Exception\RuntimeException * @return string */ public function create($password) { $options = ['cost' => (int) $this->cost]; if (PHP_VERSION_ID < 70000) { // salt is deprecated from PHP 7.0 $salt = $this->salt ?: Rand::getBytes(self::MIN_SALT_SIZE); $options['salt'] = $salt; } return password_hash($password, PASSWORD_BCRYPT, $options); }
function __construct(array $options = array()) { // Preencher automático os valores no objeto // $hydrator = new Hydrator\ClassMethods; // $hydrator->hydrate($options, $this); (new Hydrator\ClassMethods())->hydrate($options, $this); $this->createdAt = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo')); $this->updatedAt = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo')); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
public function __construct(array $options = array()) { /* $hydrator = new Hydrator\ClassMethods(); $hydrator->hydrate($options, $this); */ (new Hydrator\ClassMethods())->hydrate($options, $this); $this->createdAt = new \DateTime("now"); $this->updateAt = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, TRUE)); $this->activationKey = md5($this->email . $this->salt); }
public function __construct(array $options = array()) { (new Hydrator\ClassMethods())->hydrate($options, $this); // recebe o array $options que é passado no construtor /* $hydrator = new Hydrator\ClassMethods; $hydrator->hydrate($options, $this); */ $this->createdAt = new \DateTime("now"); $this->updatedAt = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
public function __construct(array $options = array()) { /* $hydrator = new Hydrator\ClassMethods; $hydrator->hydrate($options, $this); */ $this->createdAt = new \DateTime("now"); $this->updatedAt = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); (new Hydrator\ClassMethods())->hydrate($options, $this); // recebe o array $options que é passado no construtoressa linha tem que ser por ultimo para gravar a senha corretamente }
public function keygen($pass = null) { $uniqueRandonStr = function ($lenght) { $bytes = openssl_random_pseudo_bytes($lenght); return bin2hex($bytes); }; if ($pass == null) { $pass = $uniqueRandonStr(32); } $salt = Rand::getBytes(strlen($pass), true); $key = Pbkdf2::calc('sha256', $pass, $salt, 10000, strlen($pass) * 2); return $key; }
public function formRand() { $bytes = Rand::getBytes(32, true); $this->data->bytes = "Random bytes (in Base64): " . base64_encode($bytes); $boolean = Rand::getBoolean(); $this->data->boolean = "Random boolean: " . ($boolean ? 'true' : 'false'); $integer = Rand::getInteger(0, 1000); $this->data->integer = "Random integer in [0-1000]: " . $integer; $float = Rand::getFloat(); $this->data->float = "Random float in [0-1): " . $float; $string = Rand::getString(32, 'abcdefghijklmnopqrstuvwxyz', true); $this->data->string = "Random string in latin alphabet:" . $string; $this->render(); }
public function __construct(array $options = array()) { //Implementa o Hydrator nesta entidade /* As 2 linhas abaixo é igual a proxima linha descomentada $hydrator = new Hydrator\ClassMethods; $hydrator->hydrate($options, $this); */ (new Hydrator\ClassMethods())->hydrate($options, $this); $this->createdAt = new \DateTime("now"); $this->updatedAt = new \DateTime("now"); //Gera caracteres 'bizarros' para criptografar a senha de ativacao $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
public function export() { $path = __DIR__ . '/../../../../../../public/csv/'; if (!is_dir($path)) { throw new \Exception("Please make sure that 'public/csv' directory exists"); } $fileName = str_replace("/", ".", base64_encode(Rand::getBytes(6, true)) . '_' . date("Y-m-d-H:i:s") . '.csv'); $file = fopen($path . $fileName, "w"); fputcsv($file, $this->headers); foreach ($this->resultFormatedData as $data) { fputcsv($file, $data); } fclose($file); return '/csv/' . $fileName; }
/** * Bcrypt * * @param string $password * @throws Exception\RuntimeException * @return string */ public function create($password) { if (empty($this->salt)) { $salt = Rand::getBytes(self::MIN_SALT_SIZE); } else { $salt = $this->salt; } $salt64 = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); /** * Check for security flaw in the bcrypt implementation used by crypt() * @see http://php.net/security/crypt_blowfish.php */ $prefix = '$2y$'; $hash = crypt($password, $prefix . $this->cost . '$' . $salt64); if (strlen($hash) < 13) { throw new Exception\RuntimeException('Error during the bcrypt generation'); } return $hash; }
public function __construct(array $options = array()) { if (isset($options['salt']) && !empty($options['salt'])) { $this->salt = $options['salt']; } else { $this->salt = Rand::getBytes(32, true); } if (isset($options['hash']) && !empty($options['hash'])) { $this->hash = (string) $options['hash']; } if (isset($options['iterations']) && !empty($options['iterations'])) { $this->iterations = (int) $options['iterations']; } if (isset($options['outputSize']) && is_int($options['outputSize']) && $options['outputSize'] > 0) { $this->outputSize = (int) $options['outputSize']; } if (isset($options['rawOutput'])) { $this->rawOutput = (bool) $options['rawOutput']; } }
/** * Encrypt using a keyrings * * @param string $plaintext * @param array|string $keys * @return string * @throws RuntimeException */ public function encrypt($plaintext, $keys = null) { // generate a random session key $sessionKey = Rand::getBytes($this->bCipher->getCipher()->getKeySize()); // encrypt the plaintext with blockcipher algorithm $this->bCipher->setKey($sessionKey); $ciphertext = $this->bCipher->encrypt($plaintext); if (!is_array($keys)) { $keys = ['' => $keys]; } $encKeys = ''; // encrypt the session key with public keys foreach ($keys as $id => $pubkey) { if (!$pubkey instanceof PubKey && !is_string($pubkey)) { throw new Exception\RuntimeException(sprintf("The public key must be a string in PEM format or an instance of %s", PubKey::class)); } $pubkey = is_string($pubkey) ? new PubKey($pubkey) : $pubkey; $encKeys .= sprintf("%s:%s:", base64_encode($id), base64_encode($this->rsa->encrypt($sessionKey, $pubkey))); } return $encKeys . ';' . $ciphertext; }
/** * * @return string */ public function createSalt() { return Rand::getBytes(8, true); }
/** * Generate a random identifier * * @return string */ protected function generateRandomId() { return md5(Rand::getBytes(32)); }
/** * Generate CSRF token * * Generates CSRF token and stores both in {@link $hash} and element * value. * * @return void */ protected function generateHash() { if (isset(static::$hashCache[$this->getSessionName()])) { $this->hash = static::$hashCache[$this->getSessionName()]; } else { $this->hash = md5($this->getSalt() . Rand::getBytes(32) . $this->getName()); static::$hashCache[$this->getSessionName()] = $this->hash; } $this->setValue($this->hash); $this->initCsrfToken(); }
/** * Create a unique code to reset password with * * @return string */ protected function createUniqueCode() { return 'c' . substr(bin2hex(Rand::getBytes(30)), 0, 49); }
/** * Generate a key and return in 'friendly' format. * * @param string $salt - optional 32 byte salt (if not supplied one will be generated).. * * @return string - friendly */ public function generate_key($salt = null) { $salt = mb_strlen($salt) === 32 ? $salt : Rand::getBytes(32, true); $pass = Rand::getBytes(32, true); return $this->friendly(KeyGen::calc($pass, $salt, 2048, 2, 1, 32)); }
/** * In the event a private number/key has not been set by the user, * or generated by ext/openssl, a best attempt will be made to * generate a random key. Having a random number generator installed * on linux/bsd is highly recommended! The alternative is not recommended * for production unless without any other option. * * @return string */ protected function generatePrivateKey() { return Math\Rand::getBytes(strlen($this->getPrime()), true); }
/** * Encrypt then authenticate using HMAC * * @param string $data * @return string * @throws Exception\InvalidArgumentException */ public function encrypt($data) { // 0 (as integer), 0.0 (as float) & '0' (as string) will return false, though these should be allowed // Must be a string, integer, or float in order to encrypt if (is_string($data) && $data === '' || is_array($data) || is_object($data)) { throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); } // Cast to string prior to encrypting if (!is_string($data)) { $data = (string) $data; } if (empty($this->cipher)) { throw new Exception\InvalidArgumentException('No symmetric cipher specified'); } if (empty($this->key)) { throw new Exception\InvalidArgumentException('No key specified for the encryption'); } $keySize = $this->cipher->getKeySize(); // generate a random salt (IV) if the salt has not been set if (!$this->saltSetted) { $this->cipher->setSalt(Rand::getBytes($this->cipher->getSaltSize(), true)); } // generate the encryption key and the HMAC key for the authentication $hash = Pbkdf2::calc($this->getPbkdf2HashAlgorithm(), $this->getKey(), $this->getSalt(), $this->keyIteration, $keySize * 2); // set the encryption key $this->cipher->setKey(substr($hash, 0, $keySize)); // set the key for HMAC $keyHmac = substr($hash, $keySize); // encryption $ciphertext = $this->cipher->encrypt($data); // HMAC $hmac = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext); if (!$this->binaryOutput) { $ciphertext = base64_encode($ciphertext); } return $hmac . $ciphertext; }
/** * Produces string of random byte of given length. * * @param integer $len length of requested string * @return string RAW random binary string */ public static function randomBytes($len) { return Rand::getBytes($len, true); }
/** * @param mixed $password */ public function setPassword($password) { $salt = Rand::getBytes(32, true); $salt = SaltedS2k::calc('sha256', $password, $salt, 100000); $bcryp = new Bcrypt(); $bcryp->setSalt($salt); $this->password = $bcryp->create($password); }
/** * Encrypt then authenticate using HMAC * * @param string $data * @return string * @throws Exception\InvalidArgumentException */ public function encrypt($data) { if (empty($data)) { throw new Exception\InvalidArgumentException('The data to encrypt cannot be empty'); } if (empty($this->key)) { throw new Exception\InvalidArgumentException('No key specified for the encryption'); } if (empty($this->cipher)) { throw new Exception\InvalidArgumentException('No symmetric cipher specified'); } $keySize = $this->cipher->getKeySize(); $salt = $this->getSalt(); // generate a random salt (IV) if empty if (empty($salt)) { $salt = Rand::getBytes($this->cipher->getSaltSize(), true); } $this->cipher->setSalt($salt); // generate the encryption key and the HMAC key for the authentication $hash = Pbkdf2::calc(self::KEY_DERIV_HMAC, $this->getKey(), $this->cipher->getSalt(), $this->keyIteration, $keySize * 2); // set the encryption key $this->cipher->setKey(substr($hash, 0, $keySize)); // set the key for HMAC $keyHmac = substr($hash, $keySize); // encryption $ciphertext = $this->cipher->encrypt($data); // HMAC $hmac = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext); if (!$this->binaryOutput) { $ciphertext = base64_encode($ciphertext); } return $hmac . $ciphertext; }
public function __construct(array $data = array()) { (new Hydrator\ClassMethods())->hydrate($data, $this); $this->userSalt = base64_encode(Rand::getBytes(8, true)); }