Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I asked this question several years ago and, since then, my knowledge of this topic has improved.</p> <p>First of all, I mentioned I wanted random numbers for a login system. Login systems are security mechanisms. This means that any random number generators that the login system relies on should be <strong>cryptographically secure</strong>.</p> <p>PHP's <code>rand</code> and <code>mt_rand</code> are not cryptographically secure.</p> <p>In these cases, it's best to be safe than sorry. There are random number generators designed specifically to be secure, notably <a href="http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php" rel="nofollow noreferrer"><code>openssl_random_pseudo_bytes</code></a> (which is unfortunately not always available -- you must enable the OpenSSL extension for it to work). On *NIX systems (such as Linux), bytes read from <code>/dev/urandom</code> <a href="https://security.stackexchange.com/questions/3936/is-a-rand-from-dev-urandom-secure-for-a-login-key">can be used</a> as well.</p> <p>Unfortunately (for the purposes of this question), both of these approaches return binary data instead of hexadecimal. Fortunately, PHP already has a function to fix this for us, <a href="http://www.php.net/manual/en/function.bin2hex.php" rel="nofollow noreferrer"><code>bin2hex</code></a>, which works for strings of any length.</p> <p>So here's how the code would look like:</p> <pre><code>function generate_secure_random_hex_string($length) { // $length should be an even, non-negative number. // Because each byte is represented as two hex digits, we'll need the binary // string to be half as long as the hex string. $binary_length = $length / 2; // First, we'll generate the random binary string. $random_result = openssl_random_pseudo_bytes($binary_length, $cstrong); if (!$cstrong) { // The result is not cryptographically secure. Abort. // die() is just a placeholder. // There might be better ways to handle this error. die(); } //Convert the result to hexadecimal return bin2hex($random_result); } // Example: echo generate_secure_random_hex_string(32); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload