How do I encrypt passwords with PostgreSQL?

Karen Manukyan picture Karen Manukyan · Sep 6, 2013 · Viewed 36.2k times · Source

I have some problems with encoding passwords,how can I do it. Type of encoding md5

digest(data text, type text) returns bytea;
CREATE OR REPLACE FUNCTION md(bytea) returns text AS $$
    SELECT encode(digest($1, 'sha1'), 'md5')
$$ LANGUAGE SQL STRICT IMMUTABLE;

INSERT INTO "login"(login, password, employee_id)
VALUES ( 'email',crypt('password', md('md5')), 1);

*** Error ***

ERROR: syntax error at or near "digest"
SQL state: 42601
Character: 1

Answer

Mark Stosberg picture Mark Stosberg · Sep 6, 2013

digest(data text, type text) returns bytea; is not valid syntax.

I recommend using bcrypt instead. No additional function definitions are required:

INSERT into "login" (login, password, employee_id) 
     VALUES ('email',crypt('password', gen_salt('bf'));

Later...

UPDATE table SET password = crypt('password',gen_salt('bf'))

And checking the password:

SELECT ... FROM table 
    WHERE password is NOT NULL 
      AND password = crypt('password-to-test',password);

Bcrypt is recommended by Crafted Software and Jeff Atwood. The official pgcrypto docs may also be of interest.