Showing posts with label PHP Generate Salt. Show all posts
Showing posts with label PHP Generate Salt. Show all posts

Monday, 23 February 2015

PHP: Generate a salt

<?php

/**
 * This function generates a password salt as a string of x (default = 15) characters
 * in the a-zA-Z0-9!@#$%&*? range.
 * @param $max integer The number of characters in the string
 * @return string
 *
 */
function generateSalt($max = 15) {
        $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*?";
        $i = 0;
        $salt = "";
        while ($i < $max) {
            $salt .= $characterList{mt_rand(0, (strlen($characterList) - 1))};
            $i++;
        }
        return $salt;
}

?>

PHP: Generate an alpha-numeric password salt

<?php
/**
 * This function generates an alpha-numeric password salt (with a default of 32 characters)
 * @param $max integer The number of characters in the string
 *
 */
function generateSalt($max = 32) {
$baseStr = time() . rand(0, 1000000) . rand(0, 1000000);
$md5Hash = md5($baseStr);
if($max < 32){
$md5Hash = substr($md5Hash, 0, $max);
}
return $md5Hash;
}

//Usage:
/*
echo "Salt with 32 characters:\n";
echo generateSalt() . "\n";
echo "Salt with 5 characters:\n";
echo generateSalt(5) . "\n";
*/
?>