SHA512-CRYPT seems to be impossible to implement within MySQL and as far Dovecot goes, I'll admit I can't understand why they suggest using encryption to begin with. Using a strong hash as the OP suggested works at least as well and is more secure.
Since I prefer my passwords with extra salt, here's how I'm using Dovecot's SSHA512 which is the "Salted SHA512 sum of the password stored in base64":
INSERT INTO `virtual_users`
(`id`, `domain_id`, `password` , `email`)
VALUES
(NULL, '1', (SELECT REPLACE(TO_BASE64(CONCAT(UNHEX(SHA2(CONCAT('YourPasswordHere', v.salt), 512)), v.salt)), '\n', '') AS salted FROM (SELECT SHA2(RAND(), 512) AS salt) v), 'user@example.com');
Or to update a password:
UPDATE virtual_users
SET `password` = (
SELECT REPLACE(TO_BASE64(CONCAT(UNHEX(SHA2(CONCAT('YourPasswordHere', v.salt), 512)), v.salt)), '\n', '') AS salted
FROM (
SELECT SHA2(RAND(), 512) AS salt
) v
)
WHERE email = 'user@example.com';
These queries:
- Generate a random (rather lengthy) salt
- Append the salt to the password
- Get the SHA512 Hash of #2
- Convert the hash to binary
- Append the salt to #4
- Convert the whole thing to Base64
- Remove unwanted newlines added by MySQL's
TO_BASE64()
function
The result is a 256 byte long string so you may need to update your password
field to VARCHAR(256).
There are a number of tutorials that suggest using doveadm
to manually generate the encrypted password and while this works well, I find it a bit more cumbersome. For those interested you can call it like so:
doveadm pw -s SHA512-CRYPT -p "YourPasswordHere"
Even more useful is the ability to validate your generated passwords with the same utility:
doveadm auth test user@example.com YourPasswordHere