create Password Hash - Java Security

Java examples for Security:Password

Description

create Password Hash

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String password = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(createPasswordHash(password)));
    }/* ww  w . j a v a2 s .c  o  m*/

    private static final String DEFAULT_HASH_ALGORITHM = "SHA-256";
    private static final String CHAR_ENCODING = "UTF-8";

    public static byte[] createPasswordHash(String password) {
        return createPasswordHash(password, DEFAULT_HASH_ALGORITHM);
    }

    public static byte[] createPasswordHash(String password,
            String algorithm) {
        byte[] hash;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.reset();
            hash = md.digest(password.getBytes(CHAR_ENCODING));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            hash = null;
        }
        return hash;
    }
}

Related Tutorials