Java SHA-256

  • + 0 comments

    import java.nio.charset.StandardCharsets; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;

    public class Solution { public static void main(String[] args) { // Create a Scanner to read input from the user Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the input string
    
        String inputString = scanner.nextLine();
    
        // Compute the SHA-256 hash of the input string
        String hashValue = computeSHA_256Hash(inputString);
    
        // Print the hash value
        System.out.println( hashValue);
    }
    
    // Function to compute the SHA-256 hash of a given string
    public static String computeSHA_256Hash(String input) {
        try {
            // Create a MessageDigest instance for SHA-256
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
    
            // Update the digest with the input bytes
            digest.update(input.getBytes());
    
            // Compute the hash
            byte[] hashBytes = digest.digest();
    
            // Convert the hash bytes to a hexadecimal string
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                hexString.append(String.format("%02x", b));
            }
    
            // Return the hexadecimal string representation of the hash
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            // If the SHA-256 algorithm is not available, print an error message
            System.err.println("SHA-256 algorithm not available");
            e.printStackTrace();
            return null;
        }
    }
    

    }