Advertisement
Guest User

PasswordHashing2

a guest
Dec 23rd, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.22 KB | None | 0 0
  1. package foo;
  2.  
  3. import static com.google.common.base.Charsets.UTF_8;
  4. import static com.google.common.base.Preconditions.checkArgument;
  5. import static com.google.common.base.Preconditions.checkNotNull;
  6.  
  7. import java.math.BigInteger;
  8. import java.security.SecureRandom;
  9.  
  10. import com.google.common.annotations.VisibleForTesting;
  11. import com.google.common.base.Strings;
  12. import com.google.common.hash.HashCode;
  13. import com.google.common.hash.HashFunction;
  14. import com.google.common.hash.Hashing;
  15.  
  16. /**
  17.  * A utility class for creating secure password hashes as well as validating
  18.  * passwords.
  19.  *
  20.  * @see http://crackstation.net/hashing-security.html
  21.  * @see http://www.jasypt.org/howtoencryptuserpasswords.html
  22.  * @see http://seanmonstar.com/post/707158385/a-basic-lesson-in-password-hashing
  23.  */
  24. public final class PasswordHashing {
  25.  
  26.   private static final SecureRandom random = new SecureRandom();
  27.   private static final int SALT_LENGTH = 64;
  28.   private static final int ITERATION_COUNT = 1000;
  29.  
  30.   public static String hashPassword(String password) {
  31.     checkNotNull(password);
  32.     String salt = getRandomSalt();
  33.     return getHash(password, salt);
  34.   }
  35.  
  36.   private static String getHash(String password, String salt) {
  37.     HashFunction func = Hashing.sha256();
  38.     HashCode result = func.hashString(salt + password, UTF_8);
  39.     for (int i = 0; i < ITERATION_COUNT; i++) {
  40.       result = func.hashBytes(result.asBytes());
  41.     }
  42.     return new StringBuilder(result.toString())
  43.         .insert(password.length(), salt)
  44.         .toString();
  45.   }
  46.  
  47.   public static boolean validatePassword(String password, String correctHash) {
  48.     checkNotNull(password);
  49.     checkNotNull(correctHash);
  50.     checkArgument(correctHash.length() == SALT_LENGTH * 2);
  51.     String salt =
  52.         correctHash.substring(password.length(), SALT_LENGTH + password.length());
  53.     return getHash(password, salt).equals(correctHash);
  54.   }
  55.  
  56.   @VisibleForTesting
  57.   static String getRandomSalt() {
  58.     String randomHexString =
  59.         new BigInteger(SALT_LENGTH * 4, random).toString(16);
  60.     String result = Strings.padStart(randomHexString, SALT_LENGTH, '0');
  61.     return result;
  62.   }
  63.  
  64.   private PasswordHashing() {
  65.     throw new AssertionError();
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement