class BCrypt::Password


@db_password == “a paltry guess” #=> false
@db_password == “my grand secret” #=> true
# compare it after retrieval
@db_password = Password.new(@user.password)
@user.reload!
# read it back
@user.update_attribute(:password, @password)
# store it safely
@password #=> “$2a$12$C5.FIvVDS9W4AYZ/Ib37YuWd/7ozp1UaMhU28UKrfSxp2oDchbi3K”
@password = Password.create(“my grand secret”)
# hash a user’s password
include BCrypt
Example usage:
A password management class which allows you to safely store users’ passwords and compare them.

def ==(secret)

@password.to_s == @password.to_s # => True
@password.to_s == @password # => True
@password == @password.to_s # => False
@password == @password # => False
@password == secret # => True

@password = BCrypt::Password.create(secret)
secret = "my secret"

Comparison edge case/gotcha:

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

def create(secret, options = {})

@password = BCrypt::Password.create("my secret", :cost => 13)

Example:

users' passwords.
attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check
4 is twice as much work as a :cost of 3). The higher the :cost the harder it becomes for
logarithmic variable which determines how computational expensive the hash is to calculate (a :cost of
Hashes a secret, returning a BCrypt::Password instance. Takes an optional :cost option, which is a
def create(secret, options = {})
  cost = options[:cost] || BCrypt::Engine.cost
  raise ArgumentError if cost > BCrypt::Engine::MAX_COST
  Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost)))
end

def initialize(raw_hash)

Initializes a BCrypt::Password instance with the data from a stored hash.
def initialize(raw_hash)
  if valid_hash?(raw_hash)
    self.replace(raw_hash)
    @version, @cost, @salt, @checksum = split_hash(self)
  else
    raise Errors::InvalidHash.new("invalid hash")
  end
end

def split_hash(h)

Splits +h+ into version, cost, salt, and hash and returns them in that order.

split_hash(raw_hash) -> version, cost, salt, hash
call-seq:
def split_hash(h)
  _, v, c, mash = h.split('$')
  return v.to_str, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str
end

def valid_hash?(h)

def valid_hash?(h)
  /\A\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}\z/ === h
end

def valid_hash?(h)

Returns true if +h+ is a valid hash.
def valid_hash?(h)
  self.class.valid_hash?(h)
end