Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-28 23:48:30
Original
181 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!