Home  >  Article  >  Java  >  How to Hash a String with SHA-256 in Java?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 23:48:30172browse

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

Hashing a String with SHA-256 in Java

Despite the common misconception as an "encoding," SHA-256 operates as a one-way hash function. To effectively hash a String using SHA-256 in Java, you must follow these steps:

  1. Convert the String into bytes using a character encoding such as StandardCharsets.UTF_8.
  2. Create a MessageDigest instance using the SHA-256 algorithm.
  3. Compute the hash by passing the byte array to the digest object.

Code Example:

<code class="java">import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

class Sha256Hash {

    public static void main(String[] args) throws Exception {
        String text = "Some String";

        // Convert to bytes
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

        // Create SHA-256 digest
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        // Compute the hash
        byte[] hash = digest.digest(bytes);

        // Print the hash (in hexadecimal representation)
        System.out.println(toHexString(hash));
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}</code>

The above is the detailed content of How to Hash a String with SHA-256 in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn