Java XML Hash hashPass(String plaintext)

Here you can find the source of hashPass(String plaintext)

Description

Given a plaintext password, return the SHA256 hash for storage and verification.

License

Open Source License

Parameter

Parameter Description
plaintext - String to calculate SHA-256 hash of

Return

hex string of SHA-256 hash. Empty string on error, which means the algorithm was not found. Since we do not vary the algorithm, this is never expected.

Declaration

public static String hashPass(String plaintext) 

Method Source Code

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

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

public class Main {
    /**/*from  w  w  w.  java  2  s.  c  o  m*/
     * Given a plaintext password, return the SHA256 hash for storage and verification.
     * 
     * @param plaintext - String to calculate SHA-256 hash of
     * 
     * @return hex string of SHA-256 hash. Empty string on error, which means the algorithm
     * was not found. Since we do not vary the algorithm, this is never expected.
     */
    public static String hashPass(String plaintext) {
        // SHA 256 is a 32-byte output, which is too large to store as an integer
        // in sqlite (max 8 bytes). We could truncate, instead we'll convert to
        // String and store characters.
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("ERR: Unable to calculate hash, Algorithm not found.");
            return "";
        }
        md.update(plaintext.getBytes());
        byte[] result = md.digest();
        // Now we have the hash bytes in result, format as a string and return.
        return DatatypeConverter.printHexBinary(result);
    }
}

Related

  1. getHash(final byte[] data, MessageDigest algo)
  2. hash(byte[] bytes)
  3. hash(final String text, final String algorithm)
  4. hash(String data, String salt)
  5. hash512(byte[] data)
  6. hashPassword(char[] password, String salt, String hashAlgo)
  7. hashPassword(String password)
  8. hashToString(byte[] hash)
  9. sha1Hash(String s)