In the last post, Generating Random Passwords, we were able to create a random password of a length that we chose. However, we could not modify the character pool without modifying the source code.
We want to be able to supply a set of characters on the command line for the generator to use.
Let’s first add that argument to RandomCommand.php
14 15 16 17 18 19 20 21 |
protected function configure() { $this->setName("gen") ->setDescription("Generates a randomized password") ->addArgument('Password Length', InputArgument::REQUIRED, 'The length of the resulting password') ->addArgument('Character Set', InputArgument::OPTIONAL, 'The set of characters to use') ; } |
We will also need to modify the execute function in the same file.
23 24 25 26 27 28 29 30 31 32 |
protected function execute(InputInterface $input, OutputInterface $output) { $RP = new RandomPassword(); if($input->getArgument('Character Set')){ $pwd = $RP::generateRandomPassword($input->getArgument('Password Length'), $input->getArgument('Character Set')); } else{ $pwd = $RP::generateRandomPassword($input->getArgument('Password Length')); } $output->writeln($pwd); } |
The generateRandomPassword function was already set up to accept a string or array as the second argument for the character pool. It’s like I knew I would want to do this …
1 2 3 |
$ php pwdrnd gen 32 "aA" AAaaaAaaAaaaaAAaAaAaA |
Well, that works. We can now pick any character that we want to be in our pool of possible characters. This will be helpful when we need a password that can only have certain special characters, or none at all.
The repository for this post can be found on GitHub here .
The repository for this post can be found on GitLab here .
The repository for this post can be found on Lupe Code’s GitLab mirror here .