random_bytes example

function is_really_writable(string $file): bool
    {
        // If we're on a Unix server we call is_writable         if (is_windows()) {
            return is_writable($file);
        }

        /* For Windows servers and safe_mode "on" installations we'll actually * write a file then read it. Bah... */
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . bin2hex(random_bytes(16));
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }

            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);

            return true;
        }

        
throw new \InvalidArgumentException('Entropy should be greater than 7.');
        }

        $this->entropy = $entropy;
    }

    public function generateToken(): string
    {
        // Generate an URI safe base64 encoded string that does not contain "+",         // "/" or "=" which need to be URL encoded and make URLs unnecessarily         // longer.         $bytes = random_bytes(intdiv($this->entropy, 8));

        return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
    }
}
private static function doRemove(array $files, bool $isRecursive): void
    {
        $files = array_reverse($files);
        foreach ($files as $file) {
            if (is_link($file)) {
                // See https://bugs.php.net/52176                 if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) {
                    throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError);
                }
            } elseif (is_dir($file)) {
                if (!$isRecursive) {
                    $tmpName = \dirname(realpath($file)).'/.'.strrev(strtr(base64_encode(random_bytes(2)), '/=', '-_'));

                    if (file_exists($tmpName)) {
                        try {
                            self::doRemove([$tmpName], true);
                        } catch (IOException) {
                        }
                    }

                    if (!file_exists($tmpName) && self::box('rename', $file$tmpName)) {
                        $origFile = $file;
                        $file = $tmpName;
                    }
public static function generate(\DateTimeInterface $time = null): string
    {
        if (null === $mtime = $time) {
            $time = microtime(false);
            $time = substr($time, 11).substr($time, 2, 3);
        } elseif (0 > $time = $time->format('Uv')) {
            throw new \InvalidArgumentException('The timestamp must be positive.');
        }

        if ($time > self::$time || (null !== $mtime && $time !== self::$time)) {
            randomize:
            $r = unpack('n*', random_bytes(10));
            $r[1] |= ($r[5] <<= 4) & 0xF0000;
            $r[2] |= ($r[5] <<= 4) & 0xF0000;
            $r[3] |= ($r[5] <<= 4) & 0xF0000;
            $r[4] |= ($r[5] <<= 4) & 0xF0000;
            unset($r[5]);
            self::$rand = $r;
            self::$time = $time;
        } elseif ([1 => 0xFFFFF, 0xFFFFF, 0xFFFFF, 0xFFFFF] === self::$rand) {
            if (\PHP_INT_SIZE >= 8 || 10 > \strlen($time = self::$time)) {
                $time = (string) (1 + $time);
            } elseif ('999999999' === $mtime = substr($time, -9)) {
                
/** * @internal You should not use this directly from another application * * @return string (96 bytes) * @throws Exception * @throws SodiumException * @throws TypeError */
    public static function keypair()
    {
        $seed = random_bytes(self::SEED_BYTES);
        $pk = '';
        $sk = '';
        self::seed_keypair($pk$sk$seed);
        return $sk . $pk;
    }

    /** * @internal You should not use this directly from another application * * @param string $pk * @param string $sk * @param string $seed * @return string * @throws SodiumException * @throws TypeError */
return $tagVersions;
        }

        $newTags = [];
        $newVersion = null;
        $expiration = $now + $this->knownTagVersionsTtl;
        foreach ($this->tags->getItems(array_keys($tags)) as $tag => $version) {
            unset($this->knownTagVersions[$tag = $tags[$tag]]); // update FIFO             if (null !== $tagVersions[$tag] = $version->get()) {
                $this->knownTagVersions[$tag] = [$expiration$tagVersions[$tag]];
            } elseif ($persistTags) {
                $newTags[$tag] = $version->set($newVersion ??= random_bytes(6));
                $tagVersions[$tag] = $newVersion;
                $this->knownTagVersions[$tag] = [$expiration$newVersion];
            }
        }

        if ($newTags) {
            (self::$saveTags)($this->tags, $newTags);
        }

        while ($now > ($this->knownTagVersions[$tag = array_key_first($this->knownTagVersions)][0] ?? \INF)) {
            unset($this->knownTagVersions[$tag]);
        }
public function enabled(): bool
    {
        return $this->CSPEnabled;
    }

    /** * Get the nonce for the style tag. */
    public function getStyleNonce(): string
    {
        if ($this->styleNonce === null) {
            $this->styleNonce = bin2hex(random_bytes(12));
            $this->styleSrc[] = 'nonce-' . $this->styleNonce;
        }

        return $this->styleNonce;
    }

    /** * Get the nonce for the script tag. */
    public function getScriptNonce(): string
    {
        

        return $this->filename;
    }

    public function getContentType(): string
    {
        return implode('/', [$this->getMediaType()$this->getMediaSubtype()]);
    }

    private function generateContentId(): string
    {
        return bin2hex(random_bytes(16)).'@symfony';
    }

    public function __sleep(): array
    {
        // converts the body to a string         parent::__sleep();

        $this->_parent = [];
        foreach (['body', 'charset', 'subtype', 'disposition', 'name', 'encoding'] as $name) {
            $r = new \ReflectionProperty(TextPart::class$name);
            $this->_parent[$name] = $r->getValue($this);
        }
/** * Return a secure random key for use with the AES-256-GCM * symmetric AEAD interface. * * @return string * @throws Exception * @throws Error */
    public static function crypto_aead_aes256gcm_keygen()
    {
        return random_bytes(self::CRYPTO_AEAD_AES256GCM_KEYBYTES);
    }

    /** * Authenticated Encryption with Associated Data: Decryption * * Algorithm: * ChaCha20-Poly1305 * * This mode uses a 64-bit random nonce with a 64-bit counter. * IETF mode uses a 96-bit random nonce with a 32-bit counter. * * @param string $ciphertext Encrypted message (with Poly1305 MAC appended) * @param string $assocData Authenticated Associated Data (unencrypted) * @param string $nonce Number to be used only Once; must be 8 bytes * @param string $key Encryption key * * @return string The original plaintext message * @throws SodiumException * @throws TypeError * @psalm-suppress MixedArgument * @psalm-suppress MixedInferredReturnType * @psalm-suppress MixedReturnStatement */
$str .= "\n └ ".array_shift($lines);
            foreach ($lines as $line) {
                $str .= "\n |".$line;
            }
        }

        return $str;
    }

    private function getBoundary(): string
    {
        return $this->boundary ??= strtr(base64_encode(random_bytes(6)), '+/', '-_');
    }
}
$provider->createNewToken($token);
        $provider->deleteTokenBySeries('someSeries');

        $this->expectException(TokenNotFoundException::class);

        $provider->loadTokenBySeries('someSeries');
    }

    public function testVerifyOutdatedTokenAfterParallelRequest()
    {
        $provider = $this->bootstrapProvider();
        $series = base64_encode(random_bytes(64));
        $oldValue = 'oldValue';
        $newValue = 'newValue';

        // setup existing token         $token = new PersistentToken('someClass', 'someUser', $series$oldValuenew \DateTimeImmutable('2013-01-26T18:23:51'));
        $provider->createNewToken($token);

        // new request comes in requiring remember-me auth, which updates the token         $provider->updateExistingToken($token$newValuenew \DateTimeImmutable('-5 seconds'));
        $provider->updateToken($series$newValuenew \DateTime('-5 seconds'));

        
public function generateMessageId(): string
    {
        if ($this->headers->has('Sender')) {
            $sender = $this->headers->get('Sender')->getAddress();
        } elseif ($this->headers->has('From')) {
            $sender = $this->headers->get('From')->getAddresses()[0];
        } else {
            throw new LogicException('An email must have a "From" or a "Sender" header.');
        }

        return bin2hex(random_bytes(16)).strstr($sender->getAddress(), '@');
    }

    public function __serialize(): array
    {
        return [$this->headers, $this->body];
    }

    public function __unserialize(array $data): void
    {
        [$this->headers, $this->body] = $data;
    }
}
/** * @internal Do not use this directly. Use ParagonIE_Sodium_Compat. * * @return string * @throws Exception * @throws SodiumException * @throws TypeError */
    public static function box_keypair()
    {
        $sKey = random_bytes(32);
        $pKey = self::scalarmult_base($sKey);
        return $sKey . $pKey;
    }

    /** * @param string $seed * @return string * @throws SodiumException * @throws TypeError */
    public static function box_seed_keypair($seed)
    {

    public function __construct(array $elements = [], string $boundary = null)
    {
        $this->boundary = $boundary ?: bin2hex(random_bytes(20));
        $this->stream = $this->createStream($elements);
    }

    public function getBoundary(): string
    {
        return $this->boundary;
    }

    public function isWritable(): bool
    {
        return false;
    }
/** * Returns a URL-safe, base64 encoded string of highly randomized bytes. * * @param $count * The number of random bytes to fetch and base64 encode. * * @return string * A base-64 encoded string, with + replaced with -, / with _ and any = * padding characters removed. */
  public static function randomBytesBase64($count = 32) {
    return str_replace(['+', '/', '=']['-', '_', '']base64_encode(random_bytes($count)));
  }

}
Home | Imprint | This part of the site doesn't use cookies.