Search code examples
pythonpython-3.xencodinghashpython-2to3

Hashing salted string multiple times (custom password hashing)


I need to port old Python 2 code to Python 3 and I think I'm messing up with string encoding.

It's a custom password hasher.

I've tried different ways, unsuccessfully, obtaining only errors or wrong results.

This is the Python 2 code which needs to work with Python 3:

from hashlib import sha256
from base64 import b64encode

# 32 characters length string
SALT = "SQ7HqXQhrOIPEALbI7QhVjZ3DHJGhK18"
PLAIN_PASSWORD = "PLAIN_PASSWORD"
SALTED_PASSWORD = "%s{%s}" % (PLAIN_PASSWORD, SALT)

digest = ""
for i in range(100):
    digest = sha256(digest + SALTED_PASSWORD).digest()

print b64encode(digest)

Output:

Yb0W9H+R7xQDStPfBjKMjFbe05jDPK6OXrdhVWCDJrU=

Solution

  • Operate on bytes from the beginning:

    SALTED_PASSWORD = ("%s{%s}" % (PLAIN_PASSWORD, SALT)).encode()
    
    digest = b""
    for i in range(100):
        digest = sha256(digest + SALTED_PASSWORD).digest()
    
    print(b64encode(digest).decode())
    
    # Yb0W9H+R7xQDStPfBjKMjFbe05jDPK6OXrdhVWCDJrU=