java hash password

Solutions on MaxInterview for java hash password by the best coders in the world

showing results for - "java hash password"
Alexander
24 Nov 2018
1import java.security.NoSuchAlgorithmException;
2import java.security.SecureRandom;
3import java.security.spec.InvalidKeySpecException;
4import java.security.spec.KeySpec;
5import java.util.Arrays;
6import java.util.Base64;
7import java.util.regex.Matcher;
8import java.util.regex.Pattern;
9
10import javax.crypto.SecretKeyFactory;
11import javax.crypto.spec.PBEKeySpec;
12
13/**
14 * Hash passwords for storage, and test passwords against password tokens.
15 * 
16 * Instances of this class can be used concurrently by multiple threads.
17 *  
18 * @author erickson
19 * @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
20 */
21public final class PasswordAuthentication
22{
23
24  /**
25   * Each token produced by this class uses this identifier as a prefix.
26   */
27  public static final String ID = "$31$";
28
29  /**
30   * The minimum recommended cost, used by default
31   */
32  public static final int DEFAULT_COST = 16;
33
34  private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
35
36  private static final int SIZE = 128;
37
38  private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
39
40  private final SecureRandom random;
41
42  private final int cost;
43
44  public PasswordAuthentication()
45  {
46    this(DEFAULT_COST);
47  }
48
49  /**
50   * Create a password manager with a specified cost
51   * 
52   * @param cost the exponential computational cost of hashing a password, 0 to 30
53   */
54  public PasswordAuthentication(int cost)
55  {
56    iterations(cost); /* Validate cost */
57    this.cost = cost;
58    this.random = new SecureRandom();
59  }
60
61  private static int iterations(int cost)
62  {
63    if ((cost < 0) || (cost > 30))
64      throw new IllegalArgumentException("cost: " + cost);
65    return 1 << cost;
66  }
67
68  /**
69   * Hash a password for storage.
70   * 
71   * @return a secure authentication token to be stored for later authentication 
72   */
73  public String hash(char[] password)
74  {
75    byte[] salt = new byte[SIZE / 8];
76    random.nextBytes(salt);
77    byte[] dk = pbkdf2(password, salt, 1 << cost);
78    byte[] hash = new byte[salt.length + dk.length];
79    System.arraycopy(salt, 0, hash, 0, salt.length);
80    System.arraycopy(dk, 0, hash, salt.length, dk.length);
81    Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
82    return ID + cost + '$' + enc.encodeToString(hash);
83  }
84
85  /**
86   * Authenticate with a password and a stored password token.
87   * 
88   * @return true if the password and token match
89   */
90  public boolean authenticate(char[] password, String token)
91  {
92    Matcher m = layout.matcher(token);
93    if (!m.matches())
94      throw new IllegalArgumentException("Invalid token format");
95    int iterations = iterations(Integer.parseInt(m.group(1)));
96    byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
97    byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
98    byte[] check = pbkdf2(password, salt, iterations);
99    int zero = 0;
100    for (int idx = 0; idx < check.length; ++idx)
101      zero |= hash[salt.length + idx] ^ check[idx];
102    return zero == 0;
103  }
104
105  private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
106  {
107    KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
108    try {
109      SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
110      return f.generateSecret(spec).getEncoded();
111    }
112    catch (NoSuchAlgorithmException ex) {
113      throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
114    }
115    catch (InvalidKeySpecException ex) {
116      throw new IllegalStateException("Invalid SecretKeyFactory", ex);
117    }
118  }
119
120  /**
121   * Hash a password in an immutable {@code String}. 
122   * 
123   * <p>Passwords should be stored in a {@code char[]} so that it can be filled 
124   * with zeros after use instead of lingering on the heap and elsewhere.
125   * 
126   * @deprecated Use {@link #hash(char[])} instead
127   */
128  @Deprecated
129  public String hash(String password)
130  {
131    return hash(password.toCharArray());
132  }
133
134  /**
135   * Authenticate with a password in an immutable {@code String} and a stored 
136   * password token. 
137   * 
138   * @deprecated Use {@link #authenticate(char[],String)} instead.
139   * @see #hash(String)
140   */
141  @Deprecated
142  public boolean authenticate(String password, String token)
143  {
144    return authenticate(password.toCharArray(), token);
145  }
146
147}
queries leading to this page
bcrypt hash generator javajava password hashjava salt and hash passwordhash passwor javahash passwordjava hashpasswordpassword hash 28 24password 2cpassword default 29 javajava hash and salt usernamehash password java easyjava hash bycrptyhow to use algorithm to store passwords in javapasswordhash javajava password hash functionbcrypt javahow to hash password javajava password hashing examplehash password javahashing security in javajava password hashingbest library to hash password in java 8how to create hash password javahow to generate a password hash javahashing passwords in javajava hashing passwordshash string secure iun javbahashed password example javahow to hash password in jvasimple way to hash password javahashing password in javahashing of password in javabcrypt example javajava efficient login algorithmspring boot creeated hash columnjava passowrod hash 5mdmethod hash passwordjava hash passwordhashing password in swing javahow to hash a password in javapassword hashing javajava salted hash passwordhow to pinhash 5b 5d javasalt hashing javapassword hashj javapin hash value in javaspring determenistic hash functionpassword hash javacode to hash password in javahash password on javabcrypt password hashing javahow to hash a passwordin javahash passwords in javascrypt hash password and save in db javajava 8 best way to hash password how to hash a passwrod in javapassword hashcode in java springhash password in javajava 8 hash passwordhow to use hashcode for password in javahow to do password hashing in javabasic password hash javapassword hashcode in spring bootpassword hash in javahashing a password in javastore password in hashed format javajava generate registration hashhow to hash password in javapassword hashing in javajava hash and salt passwordsha256 vs bcrypt spring boothow to change password to hashcode and save in api in android kotlinhasing and salting javajava hash a passwordhash passwords javajava login salted passwordhashing passwords javajava hash password