0

I'm trying to insert hundreds of accounts into a MySQL database. I can't insert clear-text passwords and my application is expecting an SHA-1 hash for passwords. A quick online search pointed me to Python's hashlib libray.

Here's my Python code to generate a SHA-1 hash:

import hashlib
m = hashlib.sha1();
m.update("kpVtk5y6");
m.digest();

How can I use m.digest in the SQL query to store passwords?

My web application uses Java's MessageDigest.digest(mypassword.getBytes()) method to store passwords, so I need to implement something similar in Python in order to auto inject user accounts.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sapphire
  • 1,107
  • 8
  • 20
  • 35
  • Instead of using m.digest(), could you use m.hexdigest() instead? That way, you're working with ASCII strings instead of binary. – sizzzzlerz May 25 '12 at 21:00
  • Actually, I don't have to work with ASCII strings and the password field is defined as byte[] not a String. Does python have a byte[] equivalent? Java's MessageDigest.digest() returns a byte[] and I need exactly that in python. – Sapphire May 25 '12 at 21:21

1 Answers1

0

You don't need to put semicolons on the end of lines in Python.

According to https://stackoverflow.com/a/5241478/181772 what you say you are doing should work. For example:

conn = MySQLdb.connect(host='localhost')
r = conn.cursor()
r.execute('INSERT INTO users (hash) VALUES (%s)', m.digest())
conn.commit()

Because m.digest() is returning a str which is Python 2's equivalent of bytes. And the link above shows that those can be inserted into the MySQL database.

So if that's what you are already doing, it sounds like you have a mistake in your code.

Community
  • 1
  • 1
andrew cooke
  • 45,717
  • 10
  • 93
  • 143