Search code examples
pythonmysqlpostfix-mta

encrypt passwords with python in same format as postfix mysql


I am working on a Postfix Virtual Mail Server. I have directions on how to add users with MySQL. I am hoping to find a Python equivalent of what is suggested in MySQL. This is because I want users to be sending me an encrypted (hashed) password they have generated using Python.

Currently to add users it suggests this:

INSERT INTO 'servermail`.`virtual_users`
(`id`, `domain_id`, `password` , `email`)
VALUES
('1', '1', ENCRYPT('firstpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email1@example.com'),
('2', '1', ENCRYPT('secondpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email2@example.com');

I want a Python equivalent of the ENCRYPT function in MySQL that outputs an encrypted password.

ENCRYPT('firstpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))

Solution

  • You can achieve that by simply running:

    import crypt
    
    password = "test_pass"
    encrypted_password = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
    

    Note that if your MySQL uses base64 encoding, you also need to encode it after:

    import base64
    
    base64_encoded_password = base64.b64encode(str.encode(encrypted_password))
    

    SQL Example: http://sqlfiddle.com/#!9/9eecb/25257/0