Sha256 Hashes in Miranda

Here’s the translation of the SHA256 Hashes example to Java, formatted in Markdown for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in Java.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Hashes {
    public static void main(String[] args) {
        String s = "sha256 this string";

        try {
            // Here we start with a new hash.
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // Update expects bytes. If you have a string s,
            // use s.getBytes() to coerce it to bytes.
            digest.update(s.getBytes());

            // This gets the finalized hash result as a byte array.
            byte[] hashBytes = digest.digest();

            System.out.println(s);
            System.out.println(bytesToHex(hashBytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    // Helper method to convert byte array to hexadecimal string
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

Running the program computes the hash and prints it in a human-readable hex format.

$ javac SHA256Hashes.java
$ java SHA256Hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you would use MessageDigest.getInstance("SHA-512").

Note that if you need cryptographically secure hashes, you should carefully research hash strength!