Reading a Password


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


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 highline/import

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

	get_password("Whats your password? ")
	# Whats your password?
	# => "buddy"


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 }

	# Password: *****
	# => "buddy"

	get_password(Password: , false)
	# Password:
	# => "buddy"

See Also

  • The ruby-password third-party library also provides ways of generating, encrypting, and test-cracking passwords ( )



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: