Skip to content

Instantly share code, notes, and snippets.

@wttj-tech
Created March 28, 2022 08:47
Show Gist options
  • Save wttj-tech/615e2baf04735c6f102c610af355f946 to your computer and use it in GitHub Desktop.
Save wttj-tech/615e2baf04735c6f102c610af355f946 to your computer and use it in GitHub Desktop.
Password: prevent reuse
defmodule MyApp.Auth do
@doc """
## Example
iex> Bcrypt.hash_pwd_salt("azerty")
"$2b$12$24jRrK0ZzPqWXAAnZrQ1MOYF6QoMPwZ6knuGba2yyvy1wIFd9fvRW"
iex> old_encrypted_password = Bcrypt.hash_pwd_salt("azerty")
"$2b$12$Voc7tE9Ry926Siau6mQsvOFLNpGVKkkRrNfbsT0goYkmpCqZLIPI6"
iex> compare_password("azerty", old_encrypted_password)
true
iex> compare_password("Hello world", old_encrypted_password)
false
"""
def compare_password(password, old_encrypted_password) do
# retrieve salt from old encrypted password
# here the salt contains, the algorithm and the cost.
salt = String.slice(old_encrypted_password, 0..28)
# By default hash_password will generate a new salt each time
# To check if a password has been already used we try to hash
# password with the previous salt
Bcrypt.Base.hash_password(password, salt) == old_encrypted_password
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment