java

How to hash a string with sha256 in Java

In this tutorial, we are going to see how to hash a string with sha256 in Java. In cryptography, SHA is a cryptographic hash function that takes an input in bytes and returns the hash value in hexadecimal.

To calculate the cryptographic hash value in Java, the MessageDigest class is used, under the java.security package.

The SHA algorithm is initialized in a static method called getInstance(). After selecting the algorithm, it calculates the hash value and returns the results in a byte array.
 

 

Java Program to hash a string with sha256:
import java.nio.charset.*;
import java.security.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "StackHowTo";

        MessageDigest msg = MessageDigest.getInstance("SHA-256");
        byte[] hash = msg.digest(str.getBytes(StandardCharsets.UTF_8));

        // convert bytes to hexadecimal
        StringBuilder s = new StringBuilder();
        for (byte b : hash) {
            s.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        System.out.println(s.toString());
    }
}

Output:

103eea79703a164bff269fce2ee894537fc5a8c0cfa3580087ce6dd1bfccb220
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *