创建一个要求输入密码但不在代码中显示的程序
Create a program that asks for a password without showing it in the code
我想在 Ruby 中编写一个程序,可以要求输入密码并验证输入的密码是否与有效密码相对应。
问题是,我可以在 ruby 中编写一个函数来检查输入的密码是否正确,例如:
def is_valid?(password)
password == "my_password"
end
但是如果有人正在查看文件,密码就会泄露。
那我该怎么做呢?
散列密码并将散列存储为字符串。
当用户键入密码时,对其进行哈希处理并将其与哈希处理后的字符串进行比较。如果匹配,则正确,否则不正确。
这是安全的,因为您无法从散列字符串中获取原始密码。
此示例使用安全的 SHA-512,因为它不能被暴力破解(目前)。
def is_valid?(password)
hash = Digest::SHA512.hexdigest(password)
mypassword == #the hash of your password
if hash == mypassword
return true
else
return false
end
编辑:
正如@Jörg W Mittag 所建议的,就安全性而言,使用 Argon2 是更好的选择,因为它实际上用于密码散列。
关于 Argon2 的更多信息:
https://github.com/technion/ruby-argon2
--
什么是哈希?
https://en.wikipedia.org/wiki/Hash_function
--
ruby 中的散列:
http://www.informit.com/articles/article.aspx?p=2314083&seqNum=35
您可以使用 bcrypt gem.
从他们的文档中提取:
require 'bcrypt'
my_password = BCrypt::Password.create("my password")
#=> "a$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey"
my_password == "my password" #=> true
my_password == "not my password" #=> false
my_password = BCrypt::Password.new("a$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey")
my_password == "my password" #=> true
my_password == "not my password" #=> false
我想在 Ruby 中编写一个程序,可以要求输入密码并验证输入的密码是否与有效密码相对应。
问题是,我可以在 ruby 中编写一个函数来检查输入的密码是否正确,例如:
def is_valid?(password)
password == "my_password"
end
但是如果有人正在查看文件,密码就会泄露。
那我该怎么做呢?
散列密码并将散列存储为字符串。
当用户键入密码时,对其进行哈希处理并将其与哈希处理后的字符串进行比较。如果匹配,则正确,否则不正确。
这是安全的,因为您无法从散列字符串中获取原始密码。
此示例使用安全的 SHA-512,因为它不能被暴力破解(目前)。
def is_valid?(password)
hash = Digest::SHA512.hexdigest(password)
mypassword == #the hash of your password
if hash == mypassword
return true
else
return false
end
编辑:
正如@Jörg W Mittag 所建议的,就安全性而言,使用 Argon2 是更好的选择,因为它实际上用于密码散列。
关于 Argon2 的更多信息:
https://github.com/technion/ruby-argon2
--
什么是哈希?
https://en.wikipedia.org/wiki/Hash_function
--
ruby 中的散列:
http://www.informit.com/articles/article.aspx?p=2314083&seqNum=35
您可以使用 bcrypt gem.
从他们的文档中提取:
require 'bcrypt'
my_password = BCrypt::Password.create("my password")
#=> "a$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey"
my_password == "my password" #=> true
my_password == "not my password" #=> false
my_password = BCrypt::Password.new("a$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey")
my_password == "my password" #=> true
my_password == "not my password" #=> false