How to Hash a String Using SHA-256 in Java?

Question

How can I hash a String using SHA-256 in Java?

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        String hashedOutput = hashString(input);
        System.out.println("Hashed Output: " + hashedOutput);
    }

    public static String hashString(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

Answer

Hashing a string using SHA-256 in Java is straightforward with the built-in `MessageDigest` class. SHA-256 is a widely adopted hashing algorithm that produces a fixed-size (256-bit) hash value, primarily used for data integrity and password storage.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        String hashedOutput = hashString(input);
        System.out.println("Hashed Output: " + hashedOutput);
    }

    public static String hashString(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

Causes

  • Choosing the correct hashing algorithm: Ensure that SHA-256 is suitable for your use case as other algorithms may be more efficient.
  • Handling exceptions properly: Not managing exceptions can lead to runtime errors.

Solutions

  • Import the necessary `java.security.MessageDigest` class when implementing SHA-256 hashing.
  • Use the right encoding to convert the input string to bytes, typically UTF-8.
  • Implement a utility method to convert the resultant byte array to a hexadecimal string format for readability.

Common Mistakes

Mistake: Not using the correct character encoding when converting strings to bytes.

Solution: Always specify UTF-8 encoding to handle characters appropriately.

Mistake: Forgetting to handle exceptions may crash the application.

Solution: Wrap your code in try-catch blocks to manage `NoSuchAlgorithmException`.

Helpers

  • Java SHA-256
  • hash string in Java
  • SHA-256 example Java
  • Java security
  • string hashing Java

Related Questions

⦿How to Safely Compare Two Strings in Java That May Be Null

Learn how to compare two strings in Java accounting for null values efficiently with expert tips and code examples.

⦿Differences Between AtomicBoolean and Volatile Boolean in Java

Learn the key differences between AtomicBoolean and volatile boolean in Java including atomicity thread safety and use cases.

⦿Do JDBC ResultSets and Statements Need to be Closed Separately if the Connection is Already Closed?

Explore why its crucial to close JDBC ResultSets and Statements separately even after closing the Connection.

⦿How to Calculate the Intersection of Two HashSets in Java?

Learn how to find the intersection of two HashSets in Java with examples and best practices.

⦿How to Retrieve the Complete URL from an HttpServletRequest in Java?

Learn how to extract the full URL from an HttpServletRequest object in Java including tips on handling parameters and potential pitfalls.

⦿How to Check if a Java List Contains an Object with a Specific Field Value

Discover efficient methods to check if a Java List contains an object with a specific field value avoiding the need for nested loops.

⦿Understanding CascadeType.ALL in @ManyToOne JPA Relationships

Explore the implications of CascadeType.ALL in JPA ManyToOne associations and its effects when deleting related entities.

⦿How to Change the Default JDK in IntelliJ IDEA to Avoid Project Reloading

Learn how to change the default JDK in IntelliJ IDEA to streamline project importing and avoid frequent reload prompts.

⦿How to Configure Maven to Copy Dependencies into the Target/lib Directory?

Learn how to set up Maven to copy all runtime dependencies into the targetlib directory after a build. Get stepbystep guidance and solutions.

⦿How to Retrieve the Current Timestamp in Android

Learn how to get the current timestamp in Android using Java with clear code examples and explanations.

© Copyright 2025 - CodingTechRoom.com