compute Sha Hash for string and return a string - Android java.security

Android examples for java.security:MessageDigest

Description

compute Sha Hash for string and return a string

Demo Code

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {

  public static String computeSha2Hash(String data) throws NoSuchAlgorithmException {

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(data.getBytes());/*  w w w.  ja va 2  s  .c  o  m*/

    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();
  }

}

Related Tutorials