This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of "Hashing Java"

From OWASP
Jump to: navigation, search
(Clarified reasons to add salt and fixed some grammar)
m (page category)
 
(13 intermediate revisions by 5 users not shown)
Line 1: Line 1:
== Status ==
+
{|
Released 14/1/2008
+
|-
==Introduction==
+
! width="700" align="center" | <br>
 +
! width="500" align="center" | <br>
 +
|-
 +
| align="right" | [[Image:OWASP Inactive Banner.jpg|800px| link=https://www.owasp.org/index.php/OWASP_Project_Stages#tab=Inactive_Projects]]
 +
| align="right" |
  
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.
+
<br/>
In order to solve this problem, passwords must be stored encrypted. Two kinds of encryption are available:
 
* One way functions (SHA-256 SHA-1 MD5, ..;) also known as Hashing functions
 
* Reversible encryption functions (DES, AES, …).
 
However, the reversible property of encryption function is useless for credentials storing (cf. OWASP Guide v2.0.1) :
 
  
''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.''
+
==Introduction==
  
==Definition of  cryptographic Hashing function:==
+
This page helps Java developers hash passwords safely. We rely on OWASP's [[Password Storage Cheat Sheet]] to explain hashing best practice and theory.
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.
+
==Java Example==
  
A good cryptographic Hash function must have these properties:
+
    public static byte[] hashPassword( final char[] password, final byte[] salt, final int iterations, final int keyLength ) {
* 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 {
+
        try {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
+
            SecretKeyFactory skf = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA512" );
        digest.reset();
+
            PBEKeySpec spec = new PBEKeySpec( password, salt, iterations, keyLength );
        byte[] input = digest.digest(password.getBytes("UTF-8"));
+
            SecretKey key = skf.generateSecret( spec );
  }
+
            byte[] res = key.getEncoded( );
 
+
            return res;
==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|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 ? ==
 
 
 
If each password is simply hashed, identical passwords will have the same hash. There are two drawbacks to choosing to only storing the password’s hash:
 
* 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 passwords the database is large.
 
* An attacker can use a list of precomputed hashed (http://en.wikipedia.org/wiki/Rainbow_table) to break passwords in seconds.
 
 
 
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/rainbow crack resistant.
 
 
 
A 64 bits salt is recommended in RSA PKCS5 standard.
 
 
 
'''Sample java code :'''
 
  import java.security.MessageDigest;
 
 
    
 
    
 
+
        } catch( NoSuchAlgorithmException | InvalidKeySpecException e ) {
  public byte[] getHash(String password, byte[] salt) throws NoSuchAlgorithmException {
+
            throw new RuntimeException( e );
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
+
         }
        digest.reset();
+
    }
         digest.update(salt);
 
        return digest.digest(password.getBytes("UTF-8"));
 
  }
 
 
 
==Hardening against the attacker's attack==
 
  
To slow down the computation it is recommended to iterate the hash operation n times. While hashing the password n times does slow down hashing for both attackers and typical users, typical users don't really notice it being that hashing is such a small percentage of their total time interacting with the system. On the other hand, an attacker trying to crack passwords spends nearly 100% of their time hashing so hashing n times gives the appearance of slowing the attacker down by a factor of n while not noticeably affecting the typical user.
+
==Guidance==
A minimum of 1000 operations is recommended in RSA PKCS5 standard.
 
  
The stored password looks like this :
+
The password and salt arguments are arrays, as is the result of the hashPassword function.
Hash(hash(hash(hash(……….hash(password||salt)))))))))))))))
+
Sensitive data should be ''cleared'' after you have used it (set the array elements to zero).
  
To authenticate a user, the operation same as above must be performed, followed by a comparison of the two hashes.
+
The example uses a Password Based Key Derivation Function 2 (PBKDF2), as discussed in the [[Password Storage Cheat Sheet]].
  
The hash function you need to use depends of your security policy. SHA-256 or SHA-512 is recommended for long term storage.
+
The ''salt'' argument should be random data and vary for each user. It should be at least 32 bytes long. Remember to save the salt with the hashed password!
  
'''Sample java code :'''
+
The ''iterations'' argument specifies how many times the PBKDF2 executes its underlying algorithm. A higher value is safer. You need to experiment on hardware equivalent to your production systems. As a starting point, find a value that requires one half second to execute. Scaling to huge number of users is beyond the scope of this document. Remember to save the value of iterations with the hashed password!
  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("UTF-8"));
 
        for (int i = 0; i < iterationNb; i++) {
 
            digest.reset();
 
            input = digest.digest(input);
 
        }
 
        return input;
 
    }
 
  
==Complete Java Sample==
+
A keyLength of 256 is safe.
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.
+
If the example code generates a NoSuchAlgorithmException, replace PBKDF2WithHmacSHA512 with PBKDF2WithHmacSHA1. Both are adequate to the task but you may be criticized when people see "SHA1" in the specification (SHA1 can be unsafe outside of the context of PBKDF2).
  
The method ''authenticate'' is used in order to authenticate a user, the method ''createUser'' is used to create a new user.
+
The SecretKeyFactory and PBEKeySpec classes have been part of Java SE since version 1.4.
  
 +
==Reference==
  
 +
See ''Iron-Clad Java: Building Secure Web Applications'' by Manico and Detlefsen, 2015, Oracle Press.
  
 
+
[[Category:Java]]
  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("UTF-8"));
 
        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);
 
    }
 
 
 
 
 
  }
 
 
 
 
 
[[Category:OWASP Java Project]]
 

Latest revision as of 14:31, 2 February 2016



OWASP Inactive Banner.jpg


Introduction

This page helps Java developers hash passwords safely. We rely on OWASP's Password Storage Cheat Sheet to explain hashing best practice and theory.

Java Example

   public static byte[] hashPassword( final char[] password, final byte[] salt, final int iterations, final int keyLength ) {
 
       try {
           SecretKeyFactory skf = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA512" );
           PBEKeySpec spec = new PBEKeySpec( password, salt, iterations, keyLength );
           SecretKey key = skf.generateSecret( spec );
           byte[] res = key.getEncoded( );
           return res;
 
       } catch( NoSuchAlgorithmException | InvalidKeySpecException e ) {
           throw new RuntimeException( e );
       }
   }

Guidance

The password and salt arguments are arrays, as is the result of the hashPassword function. Sensitive data should be cleared after you have used it (set the array elements to zero).

The example uses a Password Based Key Derivation Function 2 (PBKDF2), as discussed in the Password Storage Cheat Sheet.

The salt argument should be random data and vary for each user. It should be at least 32 bytes long. Remember to save the salt with the hashed password!

The iterations argument specifies how many times the PBKDF2 executes its underlying algorithm. A higher value is safer. You need to experiment on hardware equivalent to your production systems. As a starting point, find a value that requires one half second to execute. Scaling to huge number of users is beyond the scope of this document. Remember to save the value of iterations with the hashed password!

A keyLength of 256 is safe.

If the example code generates a NoSuchAlgorithmException, replace PBKDF2WithHmacSHA512 with PBKDF2WithHmacSHA1. Both are adequate to the task but you may be criticized when people see "SHA1" in the specification (SHA1 can be unsafe outside of the context of PBKDF2).

The SecretKeyFactory and PBEKeySpec classes have been part of Java SE since version 1.4.

Reference

See Iron-Clad Java: Building Secure Web Applications by Manico and Detlefsen, 2015, Oracle Press.