hash Password - Java Security

Java examples for Security:Password

Description

hash Password

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import sun.misc.BASE64Encoder;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String password = "java2s.com";
        byte[] salt = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(hashPassword(password, salt));
    }//from   w w  w  .j  ava 2  s .c o m

    public static String hashPassword(String password, byte[] salt)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {

        byte[] bDigest = getHash(1000, password, salt);
        String sDigest = byteToBase64(bDigest);

        return sDigest;
    }

    public static byte[] getHash(int iterationNb, String password,
            byte[] salt) throws NoSuchAlgorithmException,
            UnsupportedEncodingException {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        digest.reset();
        digest.update(salt);
        byte[] input = digest.digest(password.getBytes("UTF-8"));
        for (int i = 0; i < iterationNb; i++) {
            digest.reset();
            input = digest.digest(input);
        }
        return input;
    }

    /**
     * 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 Tutorials