Hashed passwords.

This commit is contained in:
Magnus Åhall 2023-07-20 10:06:28 +02:00
parent 9681bd26d5
commit 54a0ee4f29
2 changed files with 35 additions and 1 deletions

View File

@ -91,7 +91,7 @@ func (session *Session) Authenticate(username, password string) (authenticated b
FROM public.user FROM public.user
WHERE WHERE
username=$1 AND username=$1 AND
password=$2 password=password_hash(SUBSTRING(password FROM 1 FOR 32), $2::bytea)
`, `,
username, username,
password, password,

34
sql/0013.sql Normal file
View File

@ -0,0 +1,34 @@
/* Required for the gen_random_bytes function */
CREATE EXTENSION pgcrypto;
CREATE FUNCTION password_hash(salt_hex char(32), pass bytea)
RETURNS char(96)
LANGUAGE plpgsql
AS
$$
BEGIN
RETURN (
SELECT
salt_hex ||
encode(
sha256(
decode(salt_hex, 'hex') || /* salt in binary */
pass /* password */
),
'hex'
)
);
END;
$$;
/* Password has to be able to accommodate 96 characters instead of previous 64.
* It can't be char(96), because then the password would be padded to 96 characters. */
ALTER TABLE public."user" ALTER COLUMN "password" TYPE varchar(96) USING "password"::varchar;
/* Update all users with salted and hashed passwords */
UPDATE public.user
SET password = password_hash( encode(gen_random_bytes(16),'hex'), password::bytea);
/* After the password hashing, all passwords are now hex encoded 32 characters salt and 64 characters hash,
* and the varchar type is not longer necessary. */
ALTER TABLE public."user" ALTER COLUMN "password" TYPE char(96) USING "password"::varchar;