Alfie Danger
Alfie Danger

Reputation: 469

Validating SHA2 in MySQL using prepared statements - Updated: Best way to store password in mysql for secure webapp with login system

I want to validate a SHA2 hash that I stored in my MySQL database (column named hash).

CREATE TABLE users (
    user_id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(150) UNIQUE NOT NULL,
    role TINYINT NOT NULL,
    salt VARCHAR(255) NOT NULL,
    hash VARCHAR(255) NOT NULL
);

My insert statements for users:

INSERT INTO users(email, role, salt, hash) 
VALUES ('[email protected]', '0', 'salt' ,SHA2(CONCAT ('partOne', 'partTwo', 'salt',), 224), '1'),

The value that is to be checked against the stored hash comes from two parameters given in the servlet (called partOne and partTwo) and salt that is individually stored for each record (column salt). I tried to do this with the following MySQL prepared statement in the servlet:

PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE hash = SHA2(CONCAT (?, ?, salt), 224)");
ps.setString(1, partOne);
ps.setString(2, partTwo);

However, this does not work (no errors but it does not return any record). So my question is can I include something that I am selecting (i.e. the salt in the SHA2 or do I need to first execute a statement where I select the salt for that user and then pass it through a '?' like the other variables? I thought this would be fine since the condition also includes the 'hash' column so I don't see a problem with it. Or is there some error in my syntax for preparedstatements?

Update:

From the comments I understand that this is a bad plan. So my question is what is the best way to securely store something like a password for a user login/logout system to protect a webapp? The idea that I had tried came from this post.

Upvotes: 0

Views: 135

Answers (0)

Related Questions