Generates a password hash that can be stored in the database or compared to the one that is stored. - Android java.security

Android examples for java.security:Hash

Description

Generates a password hash that can be stored in the database or compared to the one that is stored.

Demo Code


//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static String HASH_ALGORITHM = "SHA-256";

    /**/*from  w w w.  jav a  2  s .com*/
     * Generates a password hash that can be stored in the database
     * or compared to the one that is stored.
     * @param pass
     */
    public static String generatePasswordHash(String pass) {
        String hash = "";

        try {
            //Encrypts the password using the SHA-256 algorithm
            MessageDigest messageDigest = MessageDigest
                    .getInstance(HASH_ALGORITHM);
            messageDigest.update(pass.getBytes());
            hash = new String(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return hash;
    }
}

Related Tutorials