You are here

function genpass_password in Generate Password 8

Same name and namespace in other branches
  1. 6 genpass.module \genpass_password()
  2. 7 genpass.module \genpass_password()

Generate a new password using genpass's internal generation algorithm.

Parameters

int $length: Length of the password to generate. Minimum length is 4.

Return value

string A random password.

Throws

Drupal\genpass\InvalidCharacterSetsException After allowing other modules to alter the character sets, an error is thrown if they are no longer viable for random passwords in a very simplistic way & check.

See also

genpass_form_alter()

user_password()

1 call to genpass_password()
hook_password in ./genpass.api.php
Generate a password of a given length and retur it.

File

./genpass.module, line 55
Contains genpass.module.

Code

function genpass_password($length = 16) {

  // This array contains the list of allowable characters for the password.
  // Note that the number 0 and the letter 'O' have been removed to avoid
  // confusion between the two. The same is true of 'I', 1, and 'l'. The
  // symbols ` and | are likewise excluded.
  $character_sets = array(
    'lower_letters' => 'abcdefghijkmnopqrstuvwxyz',
    'upper_letters' => 'ABCDEFGHJKLMNPQRSTUVWXYZ',
    'digits' => '23456789',
    'special' => '!"#$%&\'()*+,-./:;<=>?@[\\]^_{}~',
  );

  // Allow another module to alter the character sets before they are used to
  // generate a password. Do sanity checks on the altered characters sets.
  \Drupal::moduleHandler()
    ->alter('genpass_character_sets', $character_sets);
  if (!is_array($character_sets)) {
    throw new InvalidCharacterSetsException('Characters sets altered to longer be a keyed array of character sets.');
  }
  $character_sets_combined = implode('', $character_sets);
  if (strlen($character_sets_combined) < $length) {
    throw new InvalidCharacterSetsException('Not enough source characters to generate a password.');
  }

  // Always include at least 1 character of each class to ensure generated
  // passwords meet simplistic password strength rules.
  $password = [];
  foreach ($character_sets as $character_set) {
    $max = strlen($character_set) - 1;
    $password[] = $character_set[random_int(0, $max)];
  }

  // Add remaining length as characters from any set.
  $max = strlen($character_sets_combined) - 1;
  for ($c = count($password); $c < $length; $c++) {
    $password[] = $character_sets_combined[random_int(0, $max)];
  }

  // Shuffle the characters around to avoid the first 4 chars always being the
  // same four character sets in order. Using shuffle() will suffice as the
  // contents of the array are already random.
  shuffle($password);
  return implode('', $password);
}