Hashing Java

Introduction :
Most of today’s applications use login/password in order to authenticate. Users often use the same login/password for different kinds of applications. If the couple is stolen, everybody can access all the applications the user has access to.

Too often passwords are stored as clear text. Thus the password can be read directly by the database’s administrator, super users or SQL Injection attack etc. The backup media is also vulnerable. In order to solve this problem, passwords must be stored encrypted. Two kinds of encryption are available: However, the reversible property of encryption function is useless for credentials storing (cf. OWASP Guide v2.0.1) :
 * One way functions (SHA-256 SHA-1 MD5, ..;) also known as Hashing functions
 * Reversible encryption functions (DES, AES, …).

''Passwords are secrets. There is no reason to decrypt them under any circumstances. Helpdesk staff should be able to set new passwords (with an audit trail, obviously), not read back old passwords. Therefore, there is no reason to store passwords in a reversible form.''

Definition of cryptographic Hashing function:
A Hash function creates a fixed length small fingerprint (or message digest) from an unlimited input string.

hash(X) ->Y         X is a infinite set and Y is a finite set.

A good cryptographic Hash function must have these properties:
 * Preimage resistant : From the function output y it must impossible to compute the input x such that hash(x)=y.
 * Second preimage resistant : from an input x1 it must impossible to compute another input x2 (different of x1) such that hash(x1)=hash(x2).
 * Collision resistant : It must be difficult to find two inputs x1 and x2 (x1<>x2) such that hash(x1)=hash(x2).

Sample java code : import java.security.MessageDigest; public byte[] getHash(String password) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset; byte[] input = digest.digest(password.getBytes); }

Credential storage.
If the password’s digest is stored in a database, an attacker should be unable to recover the password thanks to the preimage resistance. The only way to go past this would be a brute force attack, i.e. computing the hash of all possible passwords or a dictionary attack, i.e. computing all the often used password.

Why add salt ?
There are two drawbacks to choosing to only store the password’s hash:
 * It is possible to identify two identical passwords.
 * Due to the birthday paradox (http://en.wikipedia.org/wiki/Birthday_paradox), the attacker can find a password very quickly especially if the number of password is important in the database.

In order to solve these problems, a salt can be concatenated to the password before the digest operation.

A salt is a random number of a fixed length. This salt must be different for each stored entry. It must be stored as clear text next to the hashed password.

In this configuration, an attacker must handle a brute force attack on each individual password. The database is now birthday attack resistant.

A 64 bits salt is recommended in RSA PKCS5 standard.

Sample java code : import java.security.MessageDigest; public byte[] getHash(String password, byte[] salt) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.reset; digest.update(salt); return digest.digest(password.getBytes); }

Hardening against the attacker's attack
To slow down the computation it is recommended to iterate the hash operation n times. Because hashing is a fast operation, it slows down by a n factor an attacker but not a legitimate user. A minimum of 1000 operations is recommended in RSA PKCS5 standard.

The stored password looks like this : Hash(hash(hash(hash(……….hash(password||salt)))))))))))))))

To authenticate a user, the operation same as above must be performed, followed by a comparison of the two hashes.

The hash function you need to use depends of your security policy. SHA-256 or SHA-512 is recommended for long term storage.

Sample java code : import java.security.*; public byte[] getHash(int iterationNb, String password, byte[] salt) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset; digest.update(salt); byte[] input = digest.digest(password.getBytes); for (int i = 0; i < iterationNb; i++) { digest.reset; input = digest.digest(input); }       return input; }

Complete Java Sample
In order to create the table needed by this application, call the method creerTable. It creates a TABLE called CREDENTIAL, with these fields :
 * LOGIN VARCHAR (100) PRIMARY KEY
 * PASSWORD VARCHAR (32)
 * SALT VARCHAR (32)

In this database, the password and the salt are stored in Base64 representation.

The method authenticate is used in order to authenticate a user, the method createUser is used to create a new user.

package org.psafix.memopwd; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.IOException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.sql.*; import java.util.Arrays; import java.security.SecureRandom; public class Owasp { private final static int ITERATION_NUMBER = 1000; public Owasp { }   /**     * Authenticates the user with a given login and password * If password and/or login is null then always returns false. * If the user does not exist in the database returns false. * @param con Connection An open connection to a databse * @param login String The login of the user * @param password String The password of the user * @return boolean Returns true if the user is authenticated, false otherwise * @throws SQLException If the database is inconsistent or unavailable (    *           (Two users with the same login, salt or digested password altered etc.)     * @throws NoSuchAlgorithmException If the algorithm SHA-1 is not supported by the JVM     */    public boolean authenticate(Connection con, String login, String password)            throws SQLException, NoSuchAlgorithmException{        boolean authenticated=false;        PreparedStatement ps = null;        ResultSet rs = null;        try {            boolean userExist = true;            // INPUT VALIDATION            if (login==null||password==null){                // TIME RESISTANT ATTACK                // Computation time is equal to the time needed by a legitimate user                userExist = false;                login="";                password="";            }            ps = con.prepareStatement("SELECT PASSWORD, SALT FROM CREDENTIAL WHERE LOGIN = ?"); ps.setString(1, login); rs = ps.executeQuery; String digest, salt; if (rs.next) { digest = rs.getString("PASSWORD"); salt = rs.getString("SALT"); // DATABASE VALIDATION if (digest == null || salt == null) { throw new SQLException("Database inconsistant Salt or Digested Password altered"); }               if (rs.next) { // Should not append, because login is the primary key throw new SQLException("Database inconsistent two CREDENTIALS with the same LOGIN"); }           } else { // TIME RESISTANT ATTACK (Even if the user does not exist the                // Computation time is equal to the time needed for a legitimate user                digest = "000000000000000000000000000=";                salt = "00000000000=";                userExist = false;            }            byte[] bDigest = base64ToByte(digest);            byte[] bSalt = base64ToByte(salt);            // Compute the new DIGEST            byte[] proposedDigest = getHash(ITERATION_NUMBER, password, bSalt);            return Arrays.equals(proposedDigest, bDigest) && userExist;        } catch (IOException ex){            throw new SQLException("Database inconsistant Salt or Digested Password altered");        }        finally{            close(rs);            close(ps);        }    }    /**     * Inserts a new user in the database     * @param con Connection An open connection to a databse * @param login String The login of the user * @param password String The password of the user * @return boolean Returns true if the login and password are ok (not null and length(login)<=100    * @throws SQLException If the database is unavailable     * @throws NoSuchAlgorithmException If the algorithm SHA-1 or the SecureRandom is not supported by the JVM     */    public boolean createUser(Connection con, String login, String password)            throws SQLException, NoSuchAlgorithmException    {        PreparedStatement ps = null;        try {            if (login!=null&&password!=null&&login.length<=100){                // Uses a secure Random not a simple Random                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");                // Salt generation 64 bits long                byte[] bSalt = new byte[8];                random.nextBytes(bSalt);                // Digest computation                byte[] bDigest = getHash(ITERATION_NUMBER,password,bSalt); String sDigest = byteToBase64(bDigest); String sSalt = byteToBase64(bSalt); ps = con.prepareStatement("INSERT INTO CREDENTIAL (LOGIN, PASSWORD, SALT) VALUES (?,?,?)"); ps.setString(1,login); ps.setString(2,sDigest); ps.setString(3,sSalt); ps.executeUpdate; return true; } else { return false; }       } finally { close(ps); }   }    /**     * From a password, a number of iterations and a salt, * returns the corresponding digest * @param iterationNb int The number of iterations of the algorithm * @param password String The password to encrypt * @param salt byte[] The salt * @return byte[] The digested password * @throws NoSuchAlgorithmException If the algorithm doesn't exist */   public byte[] getHash(int iterationNb, String password, byte[] salt) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset; digest.update(salt); byte[] input = digest.digest(password.getBytes); for (int i = 0; i < iterationNb; i++) { digest.reset; input = digest.digest(input); }       return input; }   public void creerTable(Connection con) throws SQLException{ Statement st = null; try { st = con.createStatement; st.execute("CREATE TABLE CREDENTIAL (LOGIN VARCHAR(100) PRIMARY KEY, PASSWORD VARCHAR(32) NOT NULL, SALT VARCHAR(32) NOT NULL)"); } finally { close(st); }   }    /**     * Closes the current statement * @param ps Statement */   public void close(Statement ps) { if (ps!=null){ try { ps.close; } catch (SQLException ignore) { }       }    }    /**     * Closes the current resultset * @param ps Statement */   public void close(ResultSet rs) { if (rs!=null){ try { rs.close; } catch (SQLException ignore) { }       }    }    /**     * From a base 64 representation, returns the corresponding byte[] * @param data String The base64 representation * @return byte[] * @throws IOException */   public static byte[] base64ToByte(String data) throws IOException { BASE64Decoder decoder = new BASE64Decoder; return decoder.decodeBuffer(data); }   /**     * From a byte[] returns a base 64 representation * @param data byte[] * @return String * @throws IOException */   public static String byteToBase64(byte[] data){ BASE64Encoder endecoder = new BASE64Encoder; return endecoder.encode(data); } }