Here you can find the source of createHash(String password)
Parameter | Description |
---|---|
password | the password to hash |
public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException
//package com.java2s; import java.security.SecureRandom; import javax.crypto.spec.PBEKeySpec; import javax.xml.bind.DatatypeConverter; import javax.crypto.SecretKeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; public class Main { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; public static final int SALT_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 24; public static final int PBKDF2_ITERATIONS = 1000; /**// w w w . j ava 2 s . c om * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { return createHash(password.toCharArray()); } /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTE_SIZE]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE); // format iterations:salt:hash //return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash); return PBKDF2_ITERATIONS + ":" + toBase64(salt) + ":" + toBase64(hash); } /** * Computes the PBKDF2 hash of a password. * * @param password the password to hash. * @param salt the salt * @param iterations the iteration count (slowness factor) * @param bytes the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } /** * Converts a byte array into a hexadecimal string. * * @param array the byte array to convert * @return a length*2 character string encoding the byte array */ private static String toBase64(byte[] array) { return DatatypeConverter.printBase64Binary(array); } }