Android How to - Create SHA256 from byte array








Question

We would like to know how to create SHA256 from byte array.

Answer

The following method shows how to create a SHA256 for byte array.

//from   ww w.ja  v a 2  s  .  co m
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
  // calculate sha256
  public static byte[] sha256(byte[] input) {
    byte [] out = null;
    
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");    
      digest.reset();    
      out = digest.digest(input);     
    } catch (NoSuchAlgorithmException e) {          
      e.printStackTrace();
    }
    return out;
  }   
}