DevToolsForYou

Hash Generator in Java — Code Examples

Hash Generator in JavaUse the online tool →

Cryptographic hash functions convert input data into a fixed-size digest. SHA-256 is the current standard for security-sensitive use cases; MD5 is broken for security but still used for checksums.

Java's java.security.MessageDigest provides MD5, SHA-1, SHA-256, and SHA-512.

Java
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HashExample {

    public static String hash(String input, String algorithm) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] bytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }

    public static void main(String[] args) throws Exception {
        String input = "Hello, world!";

        System.out.println(hash(input, "SHA-256"));
        // 315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3

        System.out.println(hash(input, "MD5"));
        // 6cd3556deb0da54bca060b4c39479839

        // HMAC-SHA256
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec("secret-key".getBytes(), "HmacSHA256"));
        byte[] macBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder macHex = new StringBuilder();
        for (byte b : macBytes) macHex.append(String.format("%02x", b));
        System.out.println(macHex);
    }
}
Notes & gotchas
  • MessageDigest is not thread-safe — create a new instance per thread or use getInstance() each time.
  • Java 11+ includes HEX formatting utilities in HexFormat to replace the manual loop.
  • Use 'SHA-256' not 'SHA256' — the algorithm name requires the hyphen in Java.
Try it in your browser

Need to hash md5/sha without writing code? The Hash Generator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open Hash MD5/SHA
Hash Generator in other languages