Android SHA256 Hash Create sha256(String input)

Here you can find the source of sha256(String input)

Description

Calculated the SHA-256 hash of the given input string.

Parameter

Parameter Description
input The string that should be hashed.

Return

A hex representation of the hashed string.

Declaration

public static String sha256(String input) 

Method Source Code

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

public class Main {
    /**/*from w w  w .  j a  va  2  s .  com*/
     * Calculated the SHA-256 hash of the given input string.
     * The input string is converted to a byte array which. This is then hashed
     * and converted back to a hex encoded hash string.
     *
     * @param input
     *            The string that should be hashed.
     * @return A hex representation of the hashed string.
     */
    public static String sha256(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = md.digest(input.getBytes());

            StringBuilder output = new StringBuilder(hashedBytes.length);

            for (int i = 0; i < hashedBytes.length; i++) {
                String hex = Integer.toHexString(0xFF & hashedBytes[i]);
                if (hex.length() == 1)
                    hex = "0" + hex;
                output.append(hex);
            }

            return output.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. sha256(String string)
  2. sha256(byte[] data)
  3. sha256(byte[] data, int offset, int length)
  4. sha256(byte[] data1, byte[] data2)