Learning R: Build a Password Generator


It is not easy to create secure passwords. The best way is to let a computer do it by randomly combining lower- and upper-case letters, digits and other printable characters.

If you want to learn how to write a small function to achieve that read on!

The exact task is again taken from Rosetta Code:

Create a password generation program which will generate passwords containing random ASCII characters from the following groups:

lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !”#$%&'()*+,-./:;?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)

The generated password(s) must include at least one (of each of the four groups):

lower-case letter,
upper-case letter,
digit (numeral), and
one “other” character.

The user must be able to specify the password length and the number of passwords to generate.

The passwords should be displayed or written to a file, one per line.

The randomness should be from a system source or library.

The program should implement a help option or button which should describe the program and options when invoked.

As often in our “Learning R” posts (for more see here: Category: Learning R) we will give a few hints but give you the chance to solve it yourself (to not spoil the fun) before showing a possible solution:

  • Create a function with the arguments nl for the password length and npw for the number of passwords to be created. Also, include a logical help for the help functionality: passwords <- function(nl = 8, npw = 1, help = FALSE) {}
  • Use an if statement to return some text if help is true
  • Use a for loop for creating npw passwords
  • Use letters, LETTERS, 0:9 and c("!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "", "?", "@", "[", "]", "^", "_", "{", "|", "}", "~") for the different groups
  • Use the sample function for sampling from the four different groups
  • Start by sampling from each of the four groups to ensure that you include at least one of each
  • Use cat(..., "\n", sep = "") for printing the passwords

This should be more than enough help, now please try to build the function yourself!

Here I give one possible solution (which I also posted on Rosetta Code):

passwords <- function(nl = 8, npw = 1, help = FALSE) {
  if (help) return("gives npw passwords with nl characters each")
  if (nl < 4) nl <- 4
  spch <- c("!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "]", "^", "_", "{", "|", "}", "~")
  for(i in 1:npw) {
    pw <- c(sample(letters, 1), sample(LETTERS, 1), sample(0:9, 1), sample(spch, 1))
    pw <- c(pw, sample(c(letters, LETTERS, 0:9, spch), nl-4, replace = TRUE))
    cat(sample(pw), "\n", sep = "")
  }
}
 
set.seed(123)
passwords(help = TRUE)
## [1] "gives npw passwords with nl characters each"
 
passwords(8)
## S2XnQoy*
 
passwords(14, 5)
## :.iJ=Q7_gP?Cio
## !yUu7OL|eH;}1p
## y2{DNvV^Zl^IFe
## Tj@T19L.q1;I*]
## 6M+{)xV?i|1UJ/

When you compare that to most of the other solutions in different programming languages shown on the Rosetta Code page you will appreciate how very powerful R is!

If you have any questions or suggestions please let me know in the comments.

Hope you learned something new today, stay tuned!

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.

This site uses Akismet to reduce spam. Learn how your comment data is processed.