Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active April 24, 2020 23:53
Show Gist options
  • Save fabiolimace/503a98e047c7124a846999357f85e374 to your computer and use it in GitHub Desktop.
Save fabiolimace/503a98e047c7124a846999357f85e374 to your computer and use it in GitHub Desktop.
Function for generating password MD5 on PostgreSQL
/**
* Returns the password MD5.
*
* @param p_password the password string
* @param p_salt the salt string
* @param p_encode the output encoding: 'base64', 'hex', 'escape'.
*/
CREATE FUNCTION fn_password_md5(p_password VARCHAR, p_salt VARCHAR, p_encode VARCHAR) RETURNS VARCHAR AS $$
DECLARE
v_salt_hash BYTEA := NULL;
v_password_hash BYTEA := NULL;
v_password_encoded VARCHAR := NULL;
BEGIN
-- Generate salt hash
SELECT DECODE(MD5(p_salt), 'hex') INTO v_salt_hash;
-- Generate password hash using the salt hash
SELECT DECODE(MD5(v_salt_hash || p_password::BYTEA), 'hex') INTO v_password_hash;
-- Convert the password hash to hexadecimal
SELECT ENCODE(v_password_hash, p_encode) INTO v_password_encoded;
RETURN v_password_encoded;
END;
$$ LANGUAGE plpgsql;
-- EXAMPLE:
-- select fn_password_md5('my_password', 'my_salt', 'hex');
-- EXAMPLE OUTPUT:
-- 7d3aa9f3390108c2066a2a12ef5a9b17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment