encrypt Password Sha256 - Java Security

Java examples for Security:Password

Description

encrypt Password Sha256

Demo Code


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

public class Main {

    public static String encryptPassword(String password)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (password == null || "".equals(password)) {
            return null;
        }/* w ww .  j  a  va 2 s . c  om*/
        return getString(getHash(password));
    }

    /**
     * 
     * @brief From a byte[] returns a base 64 representation
     * @details
     * @param data
     * @return
     */
    private static String getString(byte[] data) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            sb.append(Integer.toString((data[i] & 0xff) + 0x100, 16)
                    .toUpperCase().substring(1));

        }
        return sb.toString();
    }

    /**
     * 
     * @brief From a password, a number of iterations, returns the corresponding digest
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getHash(String password)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        byte[] input = digest.digest(password.getBytes("UTF-8"));
        return input;
    }
}

Related Tutorials