MySQL and Java: Byte array not same when retrieved as it was when stored

I'm creating a table for users containing their hashed passwords and it's salt.

The issue is that when I create the user's row in the table and save the salt and password (both are byte[] stored in VARBINARY columns) and try to get that data back when the user logs back in, the returned salt and hashed password is different than it was when I created the row.

To get the data I am using ResultSet and I call resultSet.getBytes("password")

To create the row I use a query like this (removed other column data to make it simpler):

String query = String.format("insert into users (`password`, `salt`) values ('%s','%s');", user.getHashedPassword(), user.getSalt());

Could there be some conversion or something that is happening that causes this problem? Should I be using something other than VARBINARY for storing byte[]?

Jon Skeet
people
quotationmark

Could there be some conversion or something that is happening that causes this problem?

Yes. You're basically calling toString() on a byte array. That isn't going to do what you want. Did you look at the SQL you were executing?

More than that, you shouldn't be producing a SQL string like this anyway - it's an approach which is vulnerable to SQL Injection Attacks as well as conversion issues.

Instead, use a PreparedStatement with parameterized SQL, and specify the parameter values directly (PreparedStatement.setBytes etc).

More broadly than that, it would be a good idea not to roll your own authentication code at all - look for an existing library that fits in well with whatever framework you're using, that's likely to avoid any of the numerous security vulnerabilities that it's all too easy to create when doing it yourself.

people

See more on this question at Stackoverflow