Text only
random password
/raw/2412c32037a574e182a9dcd04fde0d3e/
2412c32037a574e182a9dcd04fde0d3e
text
Text only
20
2025-04-04T11:41:35
True
False
False
Apr 13, 2018 at 05:27 PM
/api/public/snipt/55/
random-password
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1"> 1</a>
<a href="#L-2"> 2</a>
<a href="#L-3"> 3</a>
<a href="#L-4"> 4</a>
<a href="#L-5"> 5</a>
<a href="#L-6"> 6</a>
<a href="#L-7"> 7</a>
<a href="#L-8"> 8</a>
<a href="#L-9"> 9</a>
<a href="#L-10">10</a>
<a href="#L-11">11</a>
<a href="#L-12">12</a>
<a href="#L-13">13</a>
<a href="#L-14">14</a>
<a href="#L-15">15</a>
<a href="#L-16">16</a>
<a href="#L-17">17</a>
<a href="#L-18">18</a>
<a href="#L-19">19</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a>$pwd = str_shuffle(bin2hex(openssl_random_pseudo_bytes(4)));
</span><span id="L-2"><a name="L-2"></a>
</span><span id="L-3"><a name="L-3"></a>OR
</span><span id="L-4"><a name="L-4"></a>
</span><span id="L-5"><a name="L-5"></a>// usage: $newpassword = generatePassword(12); // for a 12-char password, upper/lower/numbers.
</span><span id="L-6"><a name="L-6"></a>// functions that use rand() or mt_rand() are not secure according to the PHP manual.
</span><span id="L-7"><a name="L-7"></a>function getRandomBytes($nbBytes = 32)
</span><span id="L-8"><a name="L-8"></a>{
</span><span id="L-9"><a name="L-9"></a> $bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
</span><span id="L-10"><a name="L-10"></a> if (false !== $bytes && true === $strong) {
</span><span id="L-11"><a name="L-11"></a> return $bytes;
</span><span id="L-12"><a name="L-12"></a> }
</span><span id="L-13"><a name="L-13"></a> else {
</span><span id="L-14"><a name="L-14"></a> throw new \Exception("Unable to generate secure token from OpenSSL.");
</span><span id="L-15"><a name="L-15"></a> }
</span><span id="L-16"><a name="L-16"></a>}
</span><span id="L-17"><a name="L-17"></a>function generatePassword($length){
</span><span id="L-18"><a name="L-18"></a> return substr(preg_replace("/[^a-zA-Z0-9]/", "", base64_encode(getRandomBytes($length+1))),0,$length);
</span><span id="L-19"><a name="L-19"></a>}
</span></pre></div>
</td></tr></table>