Android How to - Compute SHA 256








Question

We would like to know how to compute SHA 256.

Answer

The following code shows how to create a SHA 256 hash.

The instance of MessageDigest is created by passing in the "SHA-256" string value.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//from  ww  w  .  j  a  v  a  2  s  . c o m
public class Main{

  public static String computeSha2Hash(String data)
      throws NoSuchAlgorithmException {

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(data.getBytes());

    byte byteData[] = md.digest();

    // convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
      sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
          .substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    return sb.toString();
  }
}