Android Hash Code Calculate getHashStringFromId(String id)

Here you can find the source of getHashStringFromId(String id)

Description

Create Hash (string) value from id string by using SHA-256 hash algorithm Return null if id is null or functionality is not supported by JVM

Declaration

public static String getHashStringFromId(String id) 

Method Source Code

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

public class Main {
    final protected static char[] hexArray = "0123456789ABCDEF"
            .toCharArray();//from  w w w .j  a  va 2s .  c o  m

    /** Create Hash (string) value from id string by using SHA-256 hash algorithm
     * Return null if id is null or functionality is not supported by JVM
     **/
    public static String getHashStringFromId(String id) {
        if (id == null)
            return null;

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(id.getBytes("UTF-8"));
            byte[] digest = md.digest();

            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            return null;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /** Convert Byte array to Hex (string) */
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}

Related

  1. computeWeakHash(String string)
  2. computeWeakHash(String string)
  3. getHash(String text)
  4. getHashCode(final Object... pObjects)
  5. getHashCode(final byte... pBytes)
  6. getHexDigit(String s, int i)
  7. createHash(String title, String URL, String content)
  8. createHash(String toHash)
  9. hash(int aSeed, boolean aBoolean)