Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docs to Crypto::Bcrypt #9647

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/crypto/bcrypt.cr
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,28 @@ class Crypto::Bcrypt
0x64657253, 0x63727944, 0x6f756274,
)

# Hashes the *password* using bcrypt algorithm using salt obtained via `Random::Secure.random_bytes(SALT_SIZE)`.
#
# ```
# require "crypto/bcrypt"
#
# Crypto::Bcrypt.hash_secret "secret"
# ```
def self.hash_secret(password, cost = DEFAULT_COST) : String
# We make a clone here to we don't keep a mutable reference to the original string
passwordb = password.to_unsafe.to_slice(password.bytesize + 1).clone # include leading 0
saltb = Random::Secure.random_bytes(SALT_SIZE)
new(passwordb, saltb, cost).to_s
end

# Creates a new `Crypto::Bcrypt` object from the given *password* with *salt* and *cost*.
#
# ```
# require "crypto/bcrypt"
#
# password = Crypto::Bcrypt.new "secret", "salt_of_16_chars"
# password.digest
# ```
def self.new(password : String, salt : String, cost = DEFAULT_COST)
# We make a clone here to we don't keep a mutable reference to the original string
passwordb = password.to_unsafe.to_slice(password.bytesize + 1).clone # include leading 0
Expand All @@ -65,6 +80,14 @@ class Crypto::Bcrypt
getter salt : Bytes
getter cost : Int32

# Creates a new `Crypto::Bcrypt` object from the given *password* with *salt* in bytes and *cost*.
#
# ```
# require "crypto/bcrypt"
#
# password = Crypto::Bcrypt.new "secret".to_slice, "salt_of_16_chars".to_slice
# password.digest
# ```
def initialize(@password : Bytes, @salt : Bytes, @cost = DEFAULT_COST)
raise Error.new("Invalid cost") unless COST_RANGE.includes?(cost)
raise Error.new("Invalid salt size") unless salt.size == SALT_SIZE
Expand Down