/gears/src/main/java/org/openlogics/gears/security/PasswordHash.java

https://bitbucket.org/miguelvega/openapi · Java · 197 lines · 105 code · 16 blank · 76 comment · 11 complexity · 01187e7d002dc78f68c4b862382c8ef8 MD5 · raw file

  1. package org.openlogics.gears.security;
  2. import javax.crypto.SecretKeyFactory;
  3. import javax.crypto.spec.PBEKeySpec;
  4. import java.math.BigInteger;
  5. import java.security.NoSuchAlgorithmException;
  6. import java.security.SecureRandom;
  7. import java.security.spec.InvalidKeySpecException;
  8. /**
  9. * @author Miguel Vega
  10. * @version $Id: PasswordHash.java 0, 2013-01-10 12:46 AM mvega $
  11. */
  12. public class PasswordHash {
  13. public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
  14. // The following constants may be changed without breaking existing hashes.
  15. protected static final int SALT_BYTES = 24;
  16. protected static final int HASH_BYTES = 24;
  17. protected static final int PBKDF2_ITERATIONS = 1000;
  18. protected static final int ITERATION_INDEX = 0;
  19. protected static final int SALT_INDEX = 1;
  20. protected static final int PBKDF2_INDEX = 2;
  21. public static byte[] createSalt() {
  22. // Generate a random salt
  23. SecureRandom random = new SecureRandom();
  24. byte[] salt = new byte[SALT_BYTES];
  25. random.nextBytes(salt);
  26. return salt;
  27. }
  28. /**
  29. * Returns a salted PBKDF2 hash of the password.
  30. *
  31. * @param password the password to hash
  32. * @return a salted PBKDF2 hash of the password
  33. */
  34. public static String createHash(String password)
  35. throws NoSuchAlgorithmException, InvalidKeySpecException {
  36. return createHash(password.toCharArray());
  37. }
  38. /**
  39. * Returns a salted PBKDF2 hash of the password.
  40. *
  41. * @param password the password to hash
  42. * @return a salted PBKDF2 hash of the password
  43. */
  44. public static String createHash(char[] password)
  45. throws NoSuchAlgorithmException, InvalidKeySpecException {
  46. byte[] salt = createSalt();
  47. // Hash the password
  48. byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES);
  49. // format iterations:salt:hash
  50. return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
  51. }
  52. /**
  53. * Validates a password using a hash.
  54. *
  55. * @param password the password to check
  56. * @param goodHash the hash of the valid password
  57. * @return true if the password is correct, false if not
  58. */
  59. public static boolean validatePassword(String password, String goodHash)
  60. throws NoSuchAlgorithmException, InvalidKeySpecException {
  61. return validatePassword(password.toCharArray(), goodHash);
  62. }
  63. /**
  64. * Validates a password using a hash.
  65. *
  66. * @param password the password to check
  67. * @param goodHash the hash of the valid password
  68. * @return true if the password is correct, false if not
  69. */
  70. public static boolean validatePassword(char[] password, String goodHash)
  71. throws NoSuchAlgorithmException, InvalidKeySpecException {
  72. // Decode the hash into its parameters
  73. String[] params = goodHash.split(":");
  74. int iterations = Integer.parseInt(params[ITERATION_INDEX]);
  75. byte[] salt = fromHex(params[SALT_INDEX]);
  76. byte[] hash = fromHex(params[PBKDF2_INDEX]);
  77. // Compute the hash of the provided password, using the same salt,
  78. // iteration count, and hash length
  79. byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
  80. // Compare the hashes in constant time. The password is correct if
  81. // both hashes match.
  82. return slowEquals(hash, testHash);
  83. }
  84. /**
  85. * Compares two byte arrays in length-constant time. This comparison method
  86. * is used so that password hashes cannot be extracted from an on-line
  87. * system using a timing attack and then attacked off-line.
  88. *
  89. * @param a the first byte array
  90. * @param b the second byte array
  91. * @return true if both byte arrays are the same, false if not
  92. */
  93. private static boolean slowEquals(byte[] a, byte[] b) {
  94. int diff = a.length ^ b.length;
  95. for (int i = 0; i < a.length && i < b.length; i++)
  96. diff |= a[i] ^ b[i];
  97. return diff == 0;
  98. }
  99. /**
  100. * Computes the PBKDF2 hash of a password.
  101. *
  102. * @param password the password to hash.
  103. * @param salt the salt
  104. * @param iterations the iteration count (slowness factor)
  105. * @param bytes the length of the hash to compute in bytes
  106. * @return the PBDKF2 hash of the password
  107. */
  108. private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
  109. throws NoSuchAlgorithmException, InvalidKeySpecException {
  110. PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
  111. SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
  112. return skf.generateSecret(spec).getEncoded();
  113. }
  114. /**
  115. * Converts a string of hexadecimal characters into a byte array.
  116. *
  117. * @param hex the hex string
  118. * @return the hex string decoded into a byte array
  119. */
  120. private static byte[] fromHex(String hex) {
  121. byte[] binary = new byte[hex.length() / 2];
  122. for (int i = 0; i < binary.length; i++) {
  123. binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
  124. }
  125. return binary;
  126. }
  127. /**
  128. * Converts a byte array into a hexadecimal string.
  129. *
  130. * @param array the byte array to convert
  131. * @return a length*2 character string encoding the byte array
  132. */
  133. private static String toHex(byte[] array) {
  134. BigInteger bi = new BigInteger(1, array);
  135. String hex = bi.toString(16);
  136. int paddingLength = (array.length * 2) - hex.length();
  137. if (paddingLength > 0)
  138. return String.format("%0" + paddingLength + "d", 0) + hex;
  139. else
  140. return hex;
  141. }
  142. /**
  143. * Tests the basic functionality of the PasswordHash class
  144. *
  145. * @param args ignored
  146. */
  147. public static void main(String[] args) {
  148. try {
  149. // Print out 10 hashes
  150. for (int i = 0; i < 10; i++)
  151. System.out.println(PasswordHash.createHash("p\r\nassw0Rd!"));
  152. // Test password validation
  153. boolean failure = false;
  154. System.out.println("Running tests...");
  155. for (int i = 0; i < 100; i++) {
  156. String password = "" + i;
  157. String hash = createHash(password);
  158. String secondHash = createHash(password);
  159. if (hash.equals(secondHash)) {
  160. System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
  161. failure = true;
  162. }
  163. String wrongPassword = "" + (i + 1);
  164. if (validatePassword(wrongPassword, hash)) {
  165. System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
  166. failure = true;
  167. }
  168. if (!validatePassword(password, hash)) {
  169. System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
  170. failure = true;
  171. }
  172. }
  173. if (failure)
  174. System.out.println("TESTS FAILED!");
  175. else
  176. System.out.println("TESTS PASSED!");
  177. } catch (Exception ex) {
  178. System.out.println("ERROR: " + ex);
  179. }
  180. }
  181. }