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

Hashing Java

From OWASP
Revision as of 00:39, 16 January 2016 by Markgordon (talk | contribs) (Remove theory & motivation of hashing. Instead, direct the reader to OWASP Password Storage Cheat Sheet. Replace example guidance based on Manico & Detlefsen's Iron-Clad Java: Building Secure Web Applications)

Jump to: navigation, search


OWASP Inactive Banner.jpg

Last revision (mm/dd/yy): 01/16/2016

Introduction

This page helps Java developers hash passwords safely. We rely on OWASP's Password Storage Cheat Sheet to explain the theory of hashing. Here we discuss only how Java developers can safely implement the advice in that cheat sheet.

Java Example

   public static byte[] hashPassword( final char[] password, final byte[] salt, final int iterations, final int keyLength ) {
 
   try {
       return SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA1" ).generateSecret(
           new PBEKeySpec( password, salt, iterations, keyLength )).getEncoded( );
 
   } 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 (generally, this means set the data to nulls).

The example uses a Password Based Key Derivation Function 2 (PBKDF2), as discussed in 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 interations 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.

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.