Skip to content

Instantly share code, notes, and snippets.

@AlexElvers
Created September 6, 2016 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexElvers/09d772a08d4d96140a4ed28c6295a84a to your computer and use it in GitHub Desktop.
Save AlexElvers/09d772a08d4d96140a4ed28c6295a84a to your computer and use it in GitHub Desktop.
Create doveadm password hashes in Python
"""
This function encodes the password similar to `doveadm pw -p PASSWORD -r ROUNDS -s SCHEME`, e.g.
{SHA256-CRYPT}$5$rounds=100000$vEmVf8wqYqnBHbFL$ed0W1.B1A3vw4dzXhBQjgxh7FB/lVSsmDAQahyzHJDB
"""
import crypt
def encode_password(password: str, rounds: int = None, scheme: str = None) -> str:
"""
Encode password with random salt.
SHA512 is used if no scheme is given.
"""
if scheme is None:
scheme = "SHA512"
method = getattr(crypt, "METHOD_%s" % scheme)
prefix = "$%s$" % method.ident
if rounds is not None:
prefix += "rounds=%d$" % rounds
return "{%s-CRYPT}%s" % (scheme, crypt.crypt(password, prefix + crypt.mksalt().rsplit("$", 1)[-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment