Reading a Password

Problem

You want to prompt the user for a password, or otherwise capture input without echoing it to the screen for all to see.

Solution

The ruby-password library makes this easy, but its not available as a Ruby gem. The HighLine library is available as a gem, and it can do this almost as well. You just have to turn off the terminal echo feature:

require ubygems require highline/import def get_password(prompt=Password: ) ask(prompt) { |q| q.echo = false} end get_password("Whats your password? ") # Whats your password? # => "buddy"

Discussion

In 2000, President Bill Clinton signed into law the Electronic Signatures Bill, which makes electronic signatures as binding as handwritten signatures. He signed the law by hand and then signed it electronically. As he typed the password to his electronic signature, it was was echoed to the screen. Everyone in the world saw that his password was the name of his pet dog, Buddy. Don let this happen to you: turn off echoing when gathering passwords.

Turning off echoing altogether is the safest way to gather a password, but it might make your users think your program has stopped responding to input. Its more userfriendly to echo a mask character, like an asterisk, for every character the user types. You can do this in HighLine by setting echo to the mask character instead of false:

def get_password(prompt=Password: , mask=*) ask(prompt) { |q| q.echo = mask } end get_password # Password: ***** # => "buddy" get_password(Password: , false) # Password: # => "buddy"

See Also

Категории