java - Hashed passwords updated through JDBC become corrupt. (More of encoding problem than hashing) -
i've tried following mysql utf-8 , latin-1, no avail.
i hash passwords (in case tosecurify) using sha-1 so:
if(tosecurify == null) { throw new exception("tosecurifystring must not null"); } try { messagedigest messagedigest = messagedigest.getinstance("sha-1"); byte[] sha1hashbytes = new byte[40]; messagedigest.update(tosecurify.getbytes(), 0, tosecurify.length()); sha1hashbytes = messagedigest.digest(); return new string(sha1hashbytes, "utf-8"); } catch(nosuchalgorithmexception nsae) { throw new exception("hash algorithm not supported."); } catch(unsupportedencodingexception uee) { throw new exception("encoding not supported."); }
then store in mysql database password column.
now here's tricky part can query db kind of like: there record
username=<insertusername> , password = thathashfunctionupthere(<insertpassword>);
this works great.
but now, updating records looks this:
string username = somejdbcstufftogetusername(); string password = somejdbcstufftogetpassword(); update(username, password);
the password has changed! corrupts passwords. it's on way out (when querying it) gets corrupted, never on way in. because inserts , queries work great, when value out set again, corrupts it, must on way out.
does have thoughts? on way out should encoding issues?
thanks in advance guys!
there's flaw in code.
return new string(sha1hashbytes, "utf-8");
you shouldn't treating bytes characters. should in fact convert every byte 2-character hexstring. e.g.
stringbuilder hex = new stringbuilder(sha1hashbytes.length * 2); (byte b : sha1hashbytes) { if ((b & 0xff) < 0x10) hex.append("0"); hex.append(integer.tohexstring(b & 0xff)); } return hex.tostring();
but, better use mysql's own sha1()
function. on insert
do:
string sql = "insert user (username, password) values (?, sha1(?))"; // ... preparedstatement = connection.preparestatement(sql); preparedstatement.setstring(username); preparedstatement.setstring(password); // 1 should unhashed!! int affectedrows = preparedstatement.executeupdate(); // ...
and on update
:
string sql = "update user set username = ?, password = sha1(?) id = ?"; // ... preparedstatement = connection.preparestatement(sql); preparedstatement.setstring(username); preparedstatement.setstring(password); // 1 should unhashed!! preparedstatement.setlong(id); int affectedrows = preparedstatement.executeupdate(); // ...
and on select
:
string sql = "select * user username = ? , password = sha1(?)"; // ... preparedstatement = connection.preparestatement(sql); preparedstatement.setstring(username); preparedstatement.setstring(password); // 1 should unhashed!! resultset = preparedstatement.executequery(); // ...
Comments
Post a Comment