源码
/Users/cbd/.rvm/gems/ruby-2.3.0/gems/bcrypt-3.1.11/lib/bcrypt/password.rb
# Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise.
def ==(secret)
super(BCrypt::Engine.hash_secret(secret, @salt))
end
alias_method :is_password?, :==
# 使用别名意图更明确
/Users/cbd/.rvm/gems/ruby-2.3.0/gems/bcrypt-3.1.11/lib/bcrypt/engine.rb
# Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates
# a bcrypt() password hash.
def self.hash_secret(secret, salt, _ = nil)
if valid_secret?(secret)
if valid_salt?(salt)
if RUBY_PLATFORM == "java"
Java.bcrypt_jruby.BCrypt.hashpw(secret.to_s, salt.to_s)
else
__bc_crypt(secret.to_s, salt)
end
else
raise Errors::InvalidSalt.new("invalid salt")
end
else
raise Errors::InvalidSecret.new("invalid secret")
end
end
生成token,22字符的base64串
def new_token
SecureRandom.urlsafe_base64
end
生成密码摘要,使用默认cost
def digest(ori_string)
BCrypt::Password.create(string)
end
验证密码摘要
def auth(digest,token)
BCrypt::Password.new(digest).is_password?(token)
end