0

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?

johhnry
  • 29
  • 1
  • 4

2 Answers2

2

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

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
  • Thanks it was really helpful! – johhnry May 05 '19 at 17:17
  • No problem :) :) – marsnebulasoup May 05 '19 at 17:18
  • 2
    For passwords, generally, Bcrypt is considered safer. "Generally" because with cryptography and security everything depends on the use-case and details. And "Safer" because Bcrypt is better protected against rainbow-tables. – berkes May 05 '19 at 17:23
  • 1
    Please, do not recommend SHA-512 for password hashing. It is a general-purpose cryptographic has function, not a password hash function. In modern code, you should generally prefer Argon2 or a similar algorithm. – Jörg W Mittag May 05 '19 at 18:42
1

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
CAmador
  • 1,881
  • 1
  • 11
  • 19