Storing Password Hash in MySQL

Storing password as hashed in the database is much more secure than storing either encrypted or plain text password. In MySQL, you can use a BLOB column to store the hash value.

create table UserLogon ( 
 userId integer NOT NULL,
 password blob NOT NULL,

 PRIMARY KEY (userId)
);

To insert data using SQL, use a hexadecimal format for the blob. For example:

insert into UserLogon(userId, password) values (
    (select id from UserProfile where email='user@example.com'),  
    x'5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8');

An utility that hashes a plain text password and then converts it to hex can come handy to populate the database using SQL. Here is a Java example:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

private static String getPasswordHashText(String password)
    throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.reset();
    byte[] hash = digest.digest(password.getBytes("UTF-8"));
    return DatatypeConverter.printHexBinary(hash);
}

Finally, in the server side code, do authentication like this:

public UserProfile authenticateUser(String email, String password) {
    try {
        byte hash[] = getPasswordHash(password);
        UserProfile u = getUserByEmail(email);
        UserLogon l = getUserLogon(u.getId());

        if (Arrays.equals(hash, l.getPassword())) {
            return u;
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Login failed", e);
    }
    return null;
}
private byte[] getPasswordHash(String password)
 throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.reset();
    byte[] hash = digest.digest(password.getBytes("UTF-8"));
    return hash;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s