Reading a Password






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 it's 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 'rubygems'
	require 'highline/import'

	def get_password(prompt='Password: ')
	  ask(prompt) { |q| q.echo = false}
	end

	get_password("What's your password? ")
	# What's 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't 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. It's 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



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows