1. /*
    2. * Password Hashing With PBKDF2 (http://crackstation.net/hashing-security.htm).
    3. * Copyright (c) 2013, Taylor Hornby
    4. * All rights reserved.
    5. *
    6. * Redistribution and use in source and binary forms, with or without
    7. * modification, are permitted provided that the following conditions are met:
    8. *
    9. * 1. Redistributions of source code must retain the above copyright notice,
    10. * this list of conditions and the following disclaimer.
    11. *
    12. * 2. Redistributions in binary form must reproduce the above copyright notice,
    13. * this list of conditions and the following disclaimer in the documentation
    14. * and/or other materials provided with the distribution.
    15. *
    16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    19. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    20. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    21. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    22. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    23. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    24. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    25. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    26. * POSSIBILITY OF SUCH DAMAGE.
    27. */
    28. import java.security.SecureRandom;
    29. import javax.crypto.spec.PBEKeySpec;
    30. import javax.crypto.SecretKeyFactory;
    31. import java.math.BigInteger;
    32. import java.security.NoSuchAlgorithmException;
    33. import java.security.spec.InvalidKeySpecException;
    34. /*
    35. * PBKDF2 salted password hashing.
    36. * Author: havoc AT defuse.ca
    37. * www: http://crackstation.net/hashing-security.htm
    38. */
    39. public class PasswordHash {
    40. public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
    41. // The following constants may be changed without breaking existing hashes.
    42. public static final int SALT_BYTE_SIZE = 24;
    43. public static final int HASH_BYTE_SIZE = 24;
    44. public static final int PBKDF2_ITERATIONS = 1000;
    45. public static final int ITERATION_INDEX = 0;
    46. public static final int SALT_INDEX = 1;
    47. public static final int PBKDF2_INDEX = 2;
    48. /**
    49. * Returns a salted PBKDF2 hash of the password.
    50. *
    51. * @param password the password to hash
    52. * @return a salted PBKDF2 hash of the password
    53. */
    54. public static String createHash(String password)
    55. throws NoSuchAlgorithmException, InvalidKeySpecException {
    56. return createHash(password.toCharArray());
    57. }
    58. /**
    59. * Returns a salted PBKDF2 hash of the password.
    60. *
    61. * @param password the password to hash
    62. * @return a salted PBKDF2 hash of the password
    63. */
    64. public static String createHash(char[] password)
    65. throws NoSuchAlgorithmException, InvalidKeySpecException {
    66. // Generate a random salt
    67. SecureRandom random = new SecureRandom();
    68. byte[] salt = new byte[SALT_BYTE_SIZE];
    69. random.nextBytes(salt);
    70. // Hash the password
    71. byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
    72. // format iterations:salt:hash
    73. return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
    74. }
    75. /**
    76. * Validates a password using a hash.
    77. *
    78. * @param password the password to check
    79. * @param correctHash the hash of the valid password
    80. * @return true if the password is correct, false if not
    81. */
    82. public static boolean validatePassword(String password, String correctHash)
    83. throws NoSuchAlgorithmException, InvalidKeySpecException {
    84. return validatePassword(password.toCharArray(), correctHash);
    85. }
    86. /**
    87. * Validates a password using a hash.
    88. *
    89. * @param password the password to check
    90. * @param correctHash the hash of the valid password
    91. * @return true if the password is correct, false if not
    92. */
    93. public static boolean validatePassword(char[] password, String correctHash)
    94. throws NoSuchAlgorithmException, InvalidKeySpecException {
    95. // Decode the hash into its parameters
    96. String[] params = correctHash.split(":");
    97. int iterations = Integer.parseInt(params[ITERATION_INDEX]);
    98. byte[] salt = fromHex(params[SALT_INDEX]);
    99. byte[] hash = fromHex(params[PBKDF2_INDEX]);
    100. // Compute the hash of the provided password, using the same salt,
    101. // iteration count, and hash length
    102. byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
    103. // Compare the hashes in constant time. The password is correct if
    104. // both hashes match.
    105. return slowEquals(hash, testHash);
    106. }
    107. /**
    108. * Compares two byte arrays in length-constant time. This comparison method
    109. * is used so that password hashes cannot be extracted from an on-line
    110. * system using a timing attack and then attacked off-line.
    111. *
    112. * @param a the first byte array
    113. * @param b the second byte array
    114. * @return true if both byte arrays are the same, false if not
    115. */
    116. private static boolean slowEquals(byte[] a, byte[] b) {
    117. int diff = a.length ^ b.length;
    118. for(int i = 0; i < a.length && i < b.length; i++)
    119. diff |= a[i] ^ b[i];
    120. return diff == 0;
    121. }
    122. /**
    123. * Computes the PBKDF2 hash of a password.
    124. *
    125. * @param password the password to hash.
    126. * @param salt the salt
    127. * @param iterations the iteration count (slowness factor)
    128. * @param bytes the length of the hash to compute in bytes
    129. * @return the PBDKF2 hash of the password
    130. */
    131. private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
    132. throws NoSuchAlgorithmException, InvalidKeySpecException {
    133. PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    134. SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    135. return skf.generateSecret(spec).getEncoded();
    136. }
    137. /**
    138. * Converts a string of hexadecimal characters into a byte array.
    139. *
    140. * @param hex the hex string
    141. * @return the hex string decoded into a byte array
    142. */
    143. private static byte[] fromHex(String hex) {
    144. byte[] binary = new byte[hex.length() / 2];
    145. for(int i = 0; i < binary.length; i++) {
    146. binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
    147. }
    148. return binary;
    149. }
    150. /**
    151. * Converts a byte array into a hexadecimal string.
    152. *
    153. * @param array the byte array to convert
    154. * @return a length*2 character string encoding the byte array
    155. */
    156. private static String toHex(byte[] array) {
    157. BigInteger bi = new BigInteger(1, array);
    158. String hex = bi.toString(16);
    159. int paddingLength = (array.length * 2) - hex.length();
    160. if(paddingLength > 0)
    161. return String.format("%0" + paddingLength + "d", 0) + hex;
    162. else
    163. return hex;
    164. }
    165. /**
    166. * Tests the basic functionality of the PasswordHash class
    167. *
    168. * @param args ignored
    169. */
    170. public static void main(String[] args) {
    171. try {
    172. // Print out 10 hashes
    173. for(int i = 0; i < 10; i++)
    174. System.out.println(PasswordHash.createHash("p\r\nassw0Rd!"));
    175. // Test password validation
    176. boolean failure = false;
    177. System.out.println("Running tests...");
    178. for(int i = 0; i < 100; i++) {
    179. String password = ""+i;
    180. String hash = createHash(password);
    181. String secondHash = createHash(password);
    182. if(hash.equals(secondHash)) {
    183. System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
    184. failure = true;
    185. }
    186. String wrongPassword = ""+(i+1);
    187. if(validatePassword(wrongPassword, hash)) {
    188. System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
    189. failure = true;
    190. }
    191. if(!validatePassword(password, hash)) {
    192. System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
    193. failure = true;
    194. }
    195. }
    196. if(failure)
    197. System.out.println("TESTS FAILED!");
    198. else
    199. System.out.println("TESTS PASSED!");
    200. } catch(Exception ex) {
    201. System.out.println("ERROR: " + ex);
    202. }
    203. }
    204. }