From c3ead0fbcf923a1490bf850bdd387881965ad9ce Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 4 Mar 2016 15:28:51 -0600 Subject: [PATCH] Add Salt And Hash A Password With pgcrypto as a postgres til --- README.md | 3 +- .../salt-and-hash-a-password-with-pgcrypto.md | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 postgres/salt-and-hash-a-password-with-pgcrypto.md diff --git a/README.md b/README.md index 2f795dd..217fce0 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_354 TILs and counting..._ +_355 TILs and counting..._ --- @@ -184,6 +184,7 @@ _354 TILs and counting..._ - [Pretty Print Data Sizes](postgres/pretty-print-data-sizes.md) - [Restart A Sequence](postgres/restart-a-sequence.md) - [Restarting Sequences When Truncating Tables](postgres/restarting-sequences-when-truncating-tables.md) +- [Salt And Hash A Password With pgcrypto](postgres/salt-and-hash-a-password-with-pgcrypto.md) - [Send A Command To psql](postgres/send-a-command-to-psql.md) - [Set Inclusion With hstore](postgres/set-inclusion-with-hstore.md) - [Set A Seed For The Random Number Generator](postgres/set-a-seed-for-the-random-number-generator.md) diff --git a/postgres/salt-and-hash-a-password-with-pgcrypto.md b/postgres/salt-and-hash-a-password-with-pgcrypto.md new file mode 100644 index 0000000..c3e6291 --- /dev/null +++ b/postgres/salt-and-hash-a-password-with-pgcrypto.md @@ -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.