How to hash a string with SHA-256 in Java

1 Answer

0 votes
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

public class MyClass {

    public static void main(String[] args) throws Exception {
        String str = "Java programming language";
        String hash = sha256(str);
        System.out.println(hash);
    }

    // Reusable function that returns SHA‑256 hash as hex string
    public static String sha256(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        // Useing UTF-8 to avoid platform differences
        byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));

        StringBuilder hexSB = new StringBuilder();
        for (byte b : hashBytes) {
            hexSB.append(String.format("%02x", b));
        }
        return hexSB.toString();
    }
}

        
        
/*
run:
        
b75812380eca4068933233ff33aada7227539a49020b5aa2696b539e674f366f
        
*/

 



answered Oct 7, 2023 by avibootz
edited May 1 by avibootz
...