ActiveState Code

Recipe 576894: Generate a salt


This function will generate a salt for use with passwords ranging from value a to z, A to Z and 0 to 9. The characters are sorted in a random value and can appear more than one time in the string. This way, this function is more powerful than the shuffle() function. This means that the salt could also be longer than the character list.

PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php

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

?>

Discussion

This version of the function is probably in it's final state. It will probably not change anymore.

This code snippet is provided to you courtesy of AfroSoft: http://afrosoft.co.cc/.

Sign in to comment