Developer Documentation
Java
Updated September 19, 2026

Cryptographic Hashing in Java

Compute secure SHA-256 digests and encode them as hexadecimal or Base64 in Java.

Cryptographic hash functions turn arbitrary input into a fixed-size deterministic digest. SHA-256 is a sensible default for checksums, content fingerprints, and integrity verification.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Quick start#

Java
1import java.nio.charset.StandardCharsets;2import java.security.MessageDigest;3import java.util.HexFormat;45MessageDigest md = MessageDigest.getInstance("SHA-256");6byte[] digest = md.digest("ToolPorta".getBytes(StandardCharsets.UTF_8));7String hex = HexFormat.of().formatHex(digest);8System.out.println(hex);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Hash a file#

Java
1MessageDigest md = MessageDigest.getInstance("SHA-256");2try (InputStream in = Files.newInputStream(Path.of("archive.zip"))) {3    byte[] buffer = new byte[];4    int read;5    while ((read = in.read(buffer)) != -) {6        md.update(buffer, , read);7    }8}9String checksum = HexFormat.of().formatHex(md.digest());

Important Notes#

Create a fresh MessageDigest per independent digest unless you explicitly reset it; the class is mutable and not designed for shared concurrent use.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Hashing in other languages: