1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Salt And Hash A Password With pgcrypto as a postgres til

This commit is contained in:
jbranchaud
2016-03-04 15:28:51 -06:00
parent 2d99ace53b
commit c3ead0fbcf
2 changed files with 46 additions and 1 deletions

View File

@@ -0,0 +1,44 @@
# Salt And Hash A Password With pgcrypto
The
[`pgcrypto`](http://www.postgresql.org/docs/current/static/pgcrypto.html)
extension that ships with PostgreSQL can be used to do a number of
interesting things. This includes functions for doing salted password
hashing. Using the `crypt` and `gen_salt` functions, we can securely store a
user password and later compare it to plain-text passwords for
authentication purposes.
```sql
create extensions pgcrypto;
select crypt('pa$$w0rd', gen_salt('bf'));
crypt
--------------------------------------------------------------
$2a$06$Z7wmrkYMOyLboLcULUYzNe6nHUcWywSZTt6nSrT5Xdv/VLdJ4g99K
> select (
'$2a$06$Z7wmrkYMOyLboLcULUYzNe6nHUcWywSZTt6nSrT5Xdv/VLdJ4g99K' =
crypt(
'pa$$w0rd',
'$2a$06$Z7wmrkYMOyLboLcULUYzNe6nHUcWywSZTt6nSrT5Xdv/VLdJ4g99K'
)
) as matched;
matched
---------
t
> select (
'$2a$06$Z7wmrkYMOyLboLcULUYzNe6nHUcWywSZTt6nSrT5Xdv/VLdJ4g99K' =
crypt(
'password',
'$2a$06$Z7wmrkYMOyLboLcULUYzNe6nHUcWywSZTt6nSrT5Xdv/VLdJ4g99K'
)
) as matched;
matched
---------
f
```
See the
[`pgcrypt` documentation](http://www.postgresql.org/docs/current/static/pgcrypto.html) for
more details.