How do I encrypt passwords with PostgreSQL?

前端 未结 2 1174
陌清茗
陌清茗 2021-01-31 20:48

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(byte         


        
相关标签:
2条回答
  • 2021-01-31 21:16

    I know this question is old but for those who having the same issue.

    Step 1: first check whether prcrypto is installed or not

    select e.extname, n.nspname from pg_catalog.pg_extension e left join pg_catalog.pg_namespace n on n.oid = e.extnamespace;
    

    Step 2: If it is not installed then create extension

    CREATE EXTENSION IF NOT EXISTS pgcrypto;

    Step 3: Computes a binary hash of the given data.

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

    Last Step:

    Also use encode function If you want the digest as a hexadecimal string

    SELECT encode(digest('blue', 'sha1'), 'hex');

    or

    directly sha('blue')

    0 讨论(0)
  • 2021-01-31 21:35

    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.

    0 讨论(0)
提交回复
热议问题