-1

http://www.128bitstudios.com/2011/11/21/authentication-with-sinatra/

Simple and nice Sinatra BCrypt authentication system - I would appreciate an explanation =)

I found this very nice article on a very simple authentication system made for Sinatra together using BCrypt and I think it's great and simple, with an nice continues classic code.

However, I have trouble understanding it, and yes I am a noob. I would really appreciate if some of you could explain at least some of the code to me, and the one I am especially interested in is this part

post "/signup" do
  password_salt = BCrypt::Engine.generate_salt
  password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)

  #ideally this would be saved into a database, hash used just for sample
  userTable[params[:username]] = {
    :salt => password_salt,
    :passwordhash => password_hash 
  }

  session[:username] = params[:username]
  redirect "/"
end

post "/login" do
  if userTable.has_key?(params[:username])
    user = userTable[params[:username]]
    if user[:passwordhash] == BCrypt::Engine.hash_secret(params[:password], user[:salt])
      session[:username] = params[:username]
      redirect "/"
    end
  end
  haml :error
end

I guess there isn't anything wrong with the code considering it's written by someone who is much better than me with that kind of stuff, but it could contain errors, but most likely not. Since I am quite new to both Sinatra and the use of BCrypt I would appreciate if someone could explain the procedure and the way it encrypts the password.

All the rest of the code is there when you visit the link, no point pasting it all here.

Also I think if I have understood correctly that the BCryptEngine creates a salt from the user param :password, but I can't understand how it saves the user to the table and all etceteral stuff. Thanks :)

4

1 回答 1

1

如果你想实现这样的东西,你至少应该了解你在做什么,而不是在这里简单地问。有一些简单的事情发生,例如将用户数据保存在不保留在请求之间的 Hash 中,因此除非您知道将用户数据存储在哪里,否则实现它没有意义。数据库可能是目前最好的答案。

salt 不是从用户密码创建的,它由 BCrypt 生成并存储在 userTable Hash 中。连同散列密码。在注册例程中,userTable 获得一个包含新用户的条目,但除非您将该哈希保存在某处,否则它会在下一次请求后丢失。

我建议先阅读基本的 Ruby 用法。如果您想在您的应用程序中实现安全性,那么了解您在做什么是有意义的。否则,如果安全性是安全的,它或多或少是纯粹的机会。

于 2013-02-01T08:42:35.457 回答