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:
<code class="java">byte[] bytes = text.getBytes(StandardCharsets.UTF_8);</code>
<code class="java">MessageDigest digest = MessageDigest.getInstance("SHA-256");</code>
<code class="java">digest.update(bytes);</code>
<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!