java hash password
Java
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
* Hash passwords for storage, and test passwords against password tokens.
*
* Instances of this class can be used concurrently by multiple threads.
*
* @author erickson
* @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
*/
public final class PasswordAuthentication
{
/**
* Each token produced by this class uses this identifier as a prefix.
*/
public static final String ID = "$31$";
/**
* The minimum recommended cost, used by default
*/
public static final int DEFAULT_COST = 16;
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
private static final int SIZE = 128;
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
private final SecureRandom random;
private final int cost;
public PasswordAuthentication()
{
this(DEFAULT_COST);
}
/**
* Create a password manager with a specified cost
*
* @param cost the exponential computational cost of hashing a password, 0 to 30
*/
public PasswordAuthentication(int cost)
{
iterations(cost); /* Validate cost */
this.cost = cost;
this.random = new SecureRandom();
}
private static int iterations(int cost)
{
if ((cost < 0) || (cost > 30))
throw new IllegalArgumentException("cost: " + cost);
return 1 << cost;
}
/**
* Hash a password for storage.
*
* @return a secure authentication token to be stored for later authentication
*/
public String hash(char[] password)
{
byte[] salt = new byte[SIZE / 8];
random.nextBytes(salt);
byte[] dk = pbkdf2(password, salt, 1 << cost);
byte[] hash = new byte[salt.length + dk.length];
System.arraycopy(salt, 0, hash, 0, salt.length);
System.arraycopy(dk, 0, hash, salt.length, dk.length);
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
return ID + cost + '$' + enc.encodeToString(hash);
}
/**
* Authenticate with a password and a stored password token.
*
* @return true if the password and token match
*/
public boolean authenticate(char[] password, String token)
{
Matcher m = layout.matcher(token);
if (!m.matches())
throw new IllegalArgumentException("Invalid token format");
int iterations = iterations(Integer.parseInt(m.group(1)));
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
byte[] check = pbkdf2(password, salt, iterations);
int zero = 0;
for (int idx = 0; idx < check.length; ++idx)
zero |= hash[salt.length + idx] ^ check[idx];
return zero == 0;
}
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
{
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
try {
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
return f.generateSecret(spec).getEncoded();
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
}
catch (InvalidKeySpecException ex) {
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
}
}
/**
* Hash a password in an immutable {@code String}.
*
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
* with zeros after use instead of lingering on the heap and elsewhere.
*
* @deprecated Use {@link #hash(char[])} instead
*/
@Deprecated
public String hash(String password)
{
return hash(password.toCharArray());
}
/**
* Authenticate with a password in an immutable {@code String} and a stored
* password token.
*
* @deprecated Use {@link #authenticate(char[],String)} instead.
* @see #hash(String)
*/
@Deprecated
public boolean authenticate(String password, String token)
{
return authenticate(password.toCharArray(), token);
}
}
Also in Java:
- Title
- java copy list
- Category
- Java
- Title
- android get distance between two locations kotlin
- Category
- Java
- Title
- java stack methods
- Category
- Java
- Title
- how to get length of integer in java
- Category
- Java
- Title
- shortcut to find a class in java project eclipse
- Category
- Java
- Title
- java how to initialize an array
- Category
- Java
- Title
- how to get elements of a list in java
- Category
- Java
- Title
- set preference value android
- Category
- Java
- Title
- java resource file
- Category
- Java
- Title
- java best way to concatenate strings
- Category
- Java
- Title
- array null pointer java
- Category
- Java
- Title
- calculate days between two dates in java
- Category
- Java
- Title
- how to know if String is the same java
- Category
- Java
- Title
- android dynamically create layer-list with item and shape site:stackoverflow.com
- Category
- Java
- Title
- how to make a fixed size array in java
- Category
- Java
- Title
- how to compare strings java
- Category
- Java
- Title
- raspberry stackexchange how to install the java jdk
- Category
- Java
- Title
- javafx action event enter key
- Category
- Java
- Title
- java list get first element
- Category
- Java
- Title
- java script zip function
- Category
- Java
- Title
- int to string java
- Category
- Java
- Title
- separateur JMenu swing java
- Category
- Java
- Title
- 2d array length in java
- Category
- Java
- Title
- output statement java
- Category
- Java
- Title
- java null pointer exception
- Category
- Java
- Title
- prime number program in java
- Category
- Java
- Title
- java while
- Category
- Java
- Title
- int4 spring jpa failling create command
- Category
- Java
- Title
- prime factorization java
- Category
- Java
- Title
- java 8 iterating and manipulating list
- Category
- Java
- Title
- java get input
- Category
- Java
- Title
- usaco 2018 january contest
- Category
- Java
- Title
- java create a set with values
- Category
- Java
- Title
- how to make a dictionary in java
- Category
- Java
- Title
- queue implementation in java using arraylist
- Category
- Java
- Title
- socket programming in java
- Category
- Java
- Title
- java hashmap get value
- Category
- Java
- Title
- NumSelfDivisors java
- Category
- Java
- Title
- java sort method
- Category
- Java
- Title
- int to binary string java
- Category
- Java
- Title
- how to add an item to a list in python
- Category
- Java
- Title
- how to get witdth of window android
- Category
- Java
- Title
- arraylist of double
- Category
- Java
- Title
- set java
- Category
- Java
- Title
- java how to make a string lowercase
- Category
- Java
- Title
- java parse xml string
- Category
- Java
- Title
- send variable intent
- Category
- Java
- Title
- how to test for legit email in java
- Category
- Java
- Title
- Java array nested equals
- Category
- Java
- Title
- searching in database using java
- Category
- Java
- Title
- how to add strings in java
- Category
- Java
- Title
- value receive null with post method in the java spring controller
- Category
- Java
- Title
- sort a map based on keys and values using java 8
- Category
- Java
- Title
- java question mark operator
- Category
- Java
- Title
- find the triplet sum in java linked list
- Category
- Java
- Title
- java creare costante
- Category
- Java
- Title
- how get started with LWJGL 3
- Category
- Java
- Title
- android create notification
- Category
- Java
- Title
- java calculator code
- Category
- Java
- Title
- android studio remove navigation bar
- Category
- Java
- Title
- selection sort in java
- Category
- Java
- Title
- how to initialize an array in java
- Category
- Java
- Title
- double round java integer
- Category
- Java
- Title
- declare bufferedreader java
- Category
- Java
- Title
- enum in java
- Category
- Java
- Title
- add a value to a list java in java hashmap
- Category
- Java
- Title
- import classes from another project java
- Category
- Java
- Title
- boolean checkbox swing
- Category
- Java
- Title
- java script snippet for responsive
- Category
- Java
- Title
- java code to get all leaf nodes of a xml file
- Category
- Java
- Title
- online money transfer andhra bank
- Category
- Java
- Title
- reverse number in java
- Category
- Java
- Title
- make a commet in java
- Category
- Java
- Title
- type javascirpt
- Category
- Java
- Title
- java string regexp replace
- Category
- Java
- Title
- how to iterate list in java selenium
- Category
- Java
- Title
- even or odd in java
- Category
- Java
- Title
- ndroid.support.v4.content.FileProvider
- Category
- Java
- Title
- difference between print and println in java
- Category
- Java
- Title
- Scanner library showing element not found exception
- Category
- Java
- Title
- java test if a string is a int
- Category
- Java
- Title
- how to find complement of a number in java
- Category
- Java
- Title
- java catch multiple exceptions
- Category
- Java
- Title
- bukkit java get max players
- Category
- Java
- Title
- how to take max value from priority queue in java
- Category
- Java
- Title
- Display double in decimal places java
- Category
- Java
- Title
- object orientation in java
- Category
- Java
- Title
- protect java
- Category
- Java
- Title
- how to create a list in java
- Category
- Java
- Title
- como detener un void java
- Category
- Java
- Title
- java min function
- Category
- Java
- Title
- how to import an arraylist in java
- Category
- Java
- Title
- countdown timer with seekbar
- Category
- Java
- Title
- print in one line in java
- Category
- Java
- Title
- java round double to 2 decimal places
- Category
- Java
- Title
- java date time
- Category
- Java
- Title
- how to split a string in java
- Category
- Java
- Title
- java while loop break
- Category
- Java
- Title
- java count substring occurrences in string
- Category
- Java
- Title
- how do you make a method that returns an array java
- Category
- Java