Get Password in Console with Ruby

Advertisement

Advertisement

Overview

Introduction

In Ruby 2.3, they introduced a getpass method on the IO::console class. There are no dependencies since it part of the standard library, but it's only available in versions higher than 2.3. For older versions, we'll look at an alternative method. The getpass method is similar to gets except it will not echo back what you are typing in. This is good for getting a password without printint it to the screen when you type it in. This will demonstrate how to use the method. See the official documentation for IO::console#getpass for more details. We will also look using $stdin.noecho() to wrap Kernel.gets to get a password.

Get a password

Here are two examples of getting passwords in a console without printing them back to the screen. The first uses IO::console.getpass available in 2.3+ and the second shows $stdin.noecho().

require 'io/console'

# The prompt is optional
password = IO::console.getpass "Enter Password: "
puts "Your password was #{password.length} characters long."

Another option that works is using $stdin.noecho(). You have to do a little more string manipulation and output managment but it works the same way with slightly more code.

require 'io/console'

# Another option using $stdin.noecho()
$stdout.print "Enter password: "
password = $stdin.noecho(&:gets)
password.strip!
puts "\nYour password was #{password.length} characters long."

Conclusion

You should now be able to securely get a password in a console without printing it back to the screen in a cross-platform way using Ruby.

Reference links

Advertisement

Advertisement