Explain Codes LogoExplain Codes Logo

How to hash some String with SHA-256 in Java?

java
hashing
sha-256
encoding
Anton ShumikhinbyAnton Shumikhin·Aug 22, 2024
TLDR

Here's your express ride to SHA-256 hashing in Java using MessageDigest:

import java.security.MessageDigest; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) throws Exception { String theSecret = "OpenSesame"; MessageDigest theDigest = MessageDigest.getInstance("SHA-256"); byte[] hashedBytes = theDigest.digest(theSecret.getBytes(StandardCharsets.UTF_8)); System.out.println(bytesToHex(hashedBytes)); // The Hex string we long for! } // Hex conversion better than grandma's apple pie recipe! private static String bytesToHex(byte[] hash) { StringBuilder hexString = new StringBuilder(2 * hash.length); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) { hexString.append('0'); // Because zeros have feelings too! } hexString.append(hex); } return hexString.toString(); } }

The function bytesToHex is your best friend for converting hashed bytes to a hex String.

Correct encoding and exception handling cannot be overemphasized. Use StandardCharsets.UTF_8 for consistency across platforms. Get cosy with NoSuchAlgorithmException for a rock-solid code!

Covering the bases

Choosing the encoding ref

Handling binary data like a champ means safely translating it to a hex string or base64 string. All hail safe representation of binary without corruption!

Library Magic

Apache Commons Codec or Google's Guava libraries can make your life easier than a Sunday morning. Here's how with Apache Commons Codec:

import org.apache.commons.codec.digest.DigestUtils; public class HashingExample { // One-liner hasher, because why not? public static String sha256hex(String input) { return DigestUtils.sha256Hex(input); } }

And the charming Guava way:

import com.google.common.hash.Hashing; public class HashingExample { // Hashing so easy, even your cat can do it! public static String sha256hex(String input) { return Hashing.sha256().hashString(input, StandardCharsets.UTF_8).toString(); } }

Exception handling

Play good defense with NoSuchAlgorithmException by logging or firing a custom exception. UnsupportedEncodingException is another dragon to slay when swinging from String to bytes.

Pro tips for hashing heroes

String conversion and Unicode wonders

Direct conversion from hash bytes to a String is as good an idea as pineapple on pizza! Always use encodingBase64.getEncoder().encodeToString() or your custom-made hex method.

The mystery of the irreversible hash

SHA-256 hashes are non-reversible like time travel in real life! Embrace the special property that boosts security.

Marvelous input validation

Input validation is as crucial as a cape in a superhero costume! Validate to dodge nulls, runtime errors, or unintentionally spooky hashes.

Get a secret vault for hashed data

Remember, while hashing adds a layer of mystery, the resulting hash is a sensitive kid. Treat it with care!