Home  >  Article  >  Java  >  How to Implement Secure String Hashing in Java with SHA-256?

How to Implement Secure String Hashing in Java with SHA-256?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 05:38:30155browse

How to Implement Secure String Hashing in Java with SHA-256?

Java Hash String using SHA-256

Hashing a string using SHA-256 in Java may seem like a straightforward task, but there are crucial differences between hashing and encoding that require clarification.

SHA-256 (Secure Hash Algorithm-256) is not an encoding mechanism; it's a one-way hash function. This means that when you hash a string, you produce an irreversible sequence of binary data.

To apply SHA-256 hashing in Java, follow these steps:

  1. Convert String to Bytes: Convert the input string into a byte array using a character encoding like UTF-8.
<code class="java">byte[] bytes = text.getBytes(StandardCharsets.UTF_8);</code>
  1. Create MessageDigest Instance: Instantiate the SHA-256 message digest algorithm.
<code class="java">MessageDigest digest = MessageDigest.getInstance("SHA-256");</code>
  1. Update Message Digest: Feed the byte array representing the string into the message digest.
<code class="java">digest.update(bytes);</code>
  1. Calculate Hash: Generate the hash value from the message digest.
<code class="java">byte[] hash = digest.digest();</code>

Important Note:

The resulting hash is in binary format. If you wish to represent it as a string, consider using base64 or hexadecimal encoding. Avoid using the String(byte[], String) constructor, as it may result in garbled characters.

The above is the detailed content of How to Implement Secure String Hashing in Java with SHA-256?. 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