Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-10-31 05:38:30
Original
160 people have browsed it

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>
Copy after login
  1. Create MessageDigest Instance: Instantiate the SHA-256 message digest algorithm.
<code class="java">MessageDigest digest = MessageDigest.getInstance("SHA-256");</code>
Copy after login
  1. Update Message Digest: Feed the byte array representing the string into the message digest.
<code class="java">digest.update(bytes);</code>
Copy after login
  1. Calculate Hash: Generate the hash value from the message digest.
<code class="java">byte[] hash = digest.digest();</code>
Copy after login

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!

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!