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:
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>
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!