Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Password hashing and insertion

Help
frosty024
2011-05-25
2012-09-19
  • frosty024
    frosty024
    2011-05-25

    Okay, So I'm monkeying with MySQLdb... Basically, I am creating a script that
    can be run for our administrators to simply type data and have it inserted
    into server_ftp table. Everything works, except I cannot get the hashed
    password to insert into the "password" field in the table. I'm sure there is
    an issue with my coding. Any ideas?

        import MySQLdb
    
        conn = MySQLdb.connect (host = "****",
                                user = "****",
                                passwd = "****",
                                db = "server_ftp")
    
        user = raw_input("Enter username: ")
        passwd = raw_input("Enter password: ")
        clear = raw_input("Enter password again: ")
        homed = raw_input("Enter home directory: ")
    
        import hashlib
    
        def mysql_password(passwd):
                """
                Hash string twice with SHA1 and return uppercase hex digest,
                prepended with an asterix.
    
                This function is identical to the MySQL PASSWORD() function.
                """
                pass1 = hashlib.sha1(passwd).digest()
                pass2 = hashlib.sha1(pass1).hexdigest()
                return "*" + pass2.upper()
    
        cursor = conn.cursor ()
    
        cursor.execute ("INSERT INTO vhosts (userid, password, clearpw, homedir) VALUES (%s, %s, %s, %s)", (user, passwd, clear, homed))
    
        print "Number of rows affected: %d" % cursor.rowcount
    
     
  • Andy Dustman
    Andy Dustman
    2011-05-25

    You're making it much too hard. Just change your query to make use of the
    built-in PASSWORD() functon:

    {{{

    INSERT INTO vhosts (userid, password, clearpw, homedir) VALUES (%s,
    PASSWORD(%s), %s, %s)

    }}}

    That should do the trick. But your real bug is, you never called
    mysql_password() to get the hashed password.