Created
March 28, 2022 08:47
-
-
Save wttj-tech/615e2baf04735c6f102c610af355f946 to your computer and use it in GitHub Desktop.
Password: prevent reuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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