protected function TfaRandomTrait::randomCharacters in Two-factor Authentication (TFA) 8
Generate random characters of the given length and allowable characters.
Parameters
int $length: The desired length of the returned string.
string $allowable_characters: Characters that are allowed to be return in the generated string.
Return value
string Random string of given length and allowed characters.
Throws
\Exception
3 calls to TfaRandomTrait::randomCharacters()
- TfaRandomTrait::randomInteger in src/TfaRandomTrait.php 
- Generate a random integer of the given character length.
- TfaRandomTrait::randomString in src/TfaRandomTrait.php 
- Generate a random string of the given character length.
- TfaRecoveryCode::generateCodes in src/Plugin/ TfaValidation/ TfaRecoveryCode.php 
- Generate an array of secure recovery codes.
File
- src/TfaRandomTrait.php, line 75 
Class
- TfaRandomTrait
- Trait TfaRandomTrait for generating cryptographically secure random data.
Namespace
Drupal\tfaCode
protected function randomCharacters($length, $allowable_characters) {
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
  // Start with a blank string.
  $characters = '';
  // Loop the number of times specified by $length.
  for ($i = 0; $i < $length; $i++) {
    do {
      // Find a secure random number within the range needed.
      $index = ord(random_bytes(1));
    } while ($index > $len);
    // Each iteration, pick a random character from the
    // allowable string and append it to the string we're building.
    $characters .= $allowable_characters[$index];
  }
  return $characters;
}