Ruby 验证 token

源码

/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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容