johhnry
johhnry

Reputation: 29

Create a program that asks for a password without showing it in the code

I want to write a program in Ruby that can ask for a password and verify if the password entered correspond to a valid password.

The thing is, I could write a function in ruby that could check if the password entered is the good one like :

def is_valid?(password)
  password == "my_password"
end

But then if someone is looking at the file, the password is going to be revealed.

So how do I do this?

Upvotes: 0

Views: 193

Answers (2)

marsnebulasoup
marsnebulasoup

Reputation: 2660

Hash the password and store the hash as a string.

When the user types the password, hash it and compare it to the hashed string. If it matches, it's correct otherwise it's not.

This is secure since you can't get the original password from the hashed string.

This example uses SHA-512, which is secure, since it can't be brute forced (yet).

def is_valid?(password)
    hash = Digest::SHA512.hexdigest(password) 
    mypassword == #the hash of your password
    if hash == mypassword
        return true
    else
        return false
end

Edit:

As @Jörg W Mittag suggested, using Argon2 is a better option in terms of security, since it is actually for password hashing.

More info on Argon2:

https://github.com/technion/ruby-argon2

--

What is hashing?

https://en.wikipedia.org/wiki/Hash_function

--

Hashing in ruby:

http://www.informit.com/articles/article.aspx?p=2314083&seqNum=35

https://richonrails.com/articles/hashing-data-in-ruby

Upvotes: 2

CAmador
CAmador

Reputation: 1951

You can use the bcrypt gem.

Extracted from their docs:

require 'bcrypt'

my_password = BCrypt::Password.create("my password")
#=> "$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey"

my_password == "my password"     #=> true
my_password == "not my password" #=> false

my_password = BCrypt::Password.new("$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey")
my_password == "my password"     #=> true
my_password == "not my password" #=> false

Upvotes: 1

Related Questions