Compute SHA-256 of byte array in java

Compute SHA-256 of byte array in java

You can compute the SHA-256 hash of a byte array in Java using the MessageDigest class from the java.security package. Here's an example of how to do it:

import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHA256Example { public static void main(String[] args) { // Sample byte array byte[] data = "Hello, World!".getBytes(); try { // Create a SHA-256 MessageDigest instance MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Compute the hash value byte[] hash = digest.digest(data); // Convert the hash bytes to a hexadecimal string StringBuilder hexString = new StringBuilder(); for (byte b : hash) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } // Print the SHA-256 hash System.out.println("SHA-256 Hash: " + hexString.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } 

In this example:

  1. We create a sample byte array (data) that you want to compute the SHA-256 hash for.

  2. We create an instance of the MessageDigest class using MessageDigest.getInstance("SHA-256"). This line initializes a SHA-256 MessageDigest object.

  3. We compute the hash value of the byte array using digest.digest(data).

  4. To convert the hash bytes to a human-readable hexadecimal string, we iterate through each byte of the hash and convert it to a two-digit hexadecimal representation. We then append these hexadecimal values to a StringBuilder to form the final hexadecimal string.

  5. Finally, we print the SHA-256 hash.

Make sure to handle exceptions like NoSuchAlgorithmException as shown in the example to handle any potential issues with the algorithm's availability.


More Tags

keyword smartcard-reader uiimageview debouncing buttonclick rsa discord.net required wifimanager functional-programming

More Java Questions

More Livestock Calculators

More General chemistry Calculators

More Internet Calculators

More Electrochemistry Calculators