Home  >  Article  >  Java  >  How to Hash a String with SHA-256 in Java: A Step-by-Step Guide

How to Hash a String with SHA-256 in Java: A Step-by-Step Guide

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 03:38:02309browse

How to Hash a String with SHA-256 in Java: A Step-by-Step Guide

Hashing a String with SHA-256 in Java: Unraveling the Encoding Enigma

Hashing algorithms, like SHA-256, are not encoding mechanisms; they're one-way irreversible functions. To hash a string with SHA-256 in Java, follow these steps:

  1. Encode the String as Bytes: Convert the string into a byte array using a specific character encoding, such as StandardCharsets.UTF_8. This step transforms the textual string into a binary representation.
  2. Calculate the Hash: Instantiate a MessageDigest object using the "SHA-256" algorithm. Invoke the digest method on this object, passing the byte array created in step 1. The result is a byte array containing the hashed representation.
  3. Converting to String: The hashed data is a binary value, so to represent it as a string, consider either base64 or hexadecimal encoding. Do not attempt to use the String(byte[], String) constructor, as this will lead to incorrect string representation.

For a practical example:

<code class="java">MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));</code>

This snippet demonstrates how to obtain the SHA-256 hash of a string in Java. Remember that hashing provides irreversible data transformation, typically used for cryptographic purposes or ensuring data integrity.

The above is the detailed content of How to Hash a String with SHA-256 in Java: A Step-by-Step Guide. 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