Java Hash Calculate getHash(String password, byte[] salt)

Here you can find the source of getHash(String password, byte[] salt)

Description

From a password returns the corresponding digest using a generated salt

License

Open Source License

Parameter

Parameter Description
password String The password to encrypt

Exception

Parameter Description
NoSuchAlgorithmException If the PBKDF2WithHmacSHA1 algorithm doesn't exist
InvalidKeySpecException an exception

Return

String The digested password

Declaration

public static String getHash(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import sun.misc.BASE64Encoder;

public class Main {
    private final static int ITERATION_NUMBER = 1593;

    /**//from   w w w .j  a  va2 s .c  om
     * From a password returns the corresponding digest using a generated salt
     * 
     * @param password
     *          String The password to encrypt
     * @return String The digested password
     * @throws NoSuchAlgorithmException
     *           If the PBKDF2WithHmacSHA1 algorithm doesn't exist
     * @throws InvalidKeySpecException
     */
    public static String getHash(String password, byte[] salt)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        char[] passChars = password.toCharArray();

        PBEKeySpec spec = new PBEKeySpec(passChars, salt, ITERATION_NUMBER, 512);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        byte[] hash = skf.generateSecret(spec).getEncoded();

        return byteToBase64(salt) + ":" + byteToBase64(hash);
    }

    /**
     * From a byte[] returns a base 64 representation
     * 
     * @param data
     *          byte[]
     * @return String
     * @throws IOException
     */
    public static String byteToBase64(byte[] data) {
        BASE64Encoder endecoder = new BASE64Encoder();
        return endecoder.encode(data);
    }
}

Related

  1. getHash(String input)
  2. getHash(String input)
  3. getHash(String key)
  4. getHash(String message)
  5. getHash(String pass, String algorithm)
  6. getHash(String password, byte[] salt)
  7. getHash(String password, String bsalt)
  8. getHash(String password, String salt)
  9. getHash(String password, String salt)