Java Hash Calculate getHashFromString(String str)

Here you can find the source of getHashFromString(String str)

Description

Generates a sha-256 hash from a string Taken from http://stackoverflow.com/questions/415953/generate-md5-hash-in-java

License

Apache License

Parameter

Parameter Description
str a java.lang.String object.

Return

a object.

Declaration

public static String getHashFromString(String str) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.UnsupportedEncodingException;

public class Main {
    /**/* w w  w.  j a  v  a 2  s . c o m*/
     * Generates a sha-256 hash from a string
     * Taken from http://stackoverflow.com/questions/415953/generate-md5-hash-in-java
     *
     * @param str a {@link java.lang.String} object.
     * @return a {@link java.lang.String} object.
     * @since 0.7.2
     */
    public static String getHashFromString(String str) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            byte[] array = md.digest(str.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte anArray : array) {
                sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException("Cannot calculate MD5 hash for :" + str, e);
        }
    }
}

Related

  1. getHash(String text)
  2. getHash(String valueToHash)
  3. getHash(String var)
  4. getHashChars(byte[] bytes)
  5. getHashedPassword(String plainPassword)
  6. getHashInstance(final String alg)
  7. getHashKey(String input)
  8. getHashMD5(File file)
  9. getHashMD5(String arg)