// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package encrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class TestHashing {
    // hash: byte[] -> byte[]
    public static byte[] hash(String alg, byte[] content) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(alg);
        return md.digest(content);
    }
    // Base64 encode: byte[] -> String
    private static String encode(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }
    // hash: String -> Base64 String
    public static String hash(String alg, String content) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        return encode(hash(alg, content.getBytes("UTF-8")));
    }
    // test
    private static final String TEXT = "This is some random text to be used to test encryption.";
    private static void test(String label, String alg) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        System.out.println(label + ":");
        String hashval = hash(alg, TEXT);
        System.out.println("  " + hashval);
        String hashval2 = hash(alg, TEXT + TEXT);
        System.out.println("  " + hashval2);
    }
    private static void test2() throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if(!hash("SHA-256", TEXT).equals("oJM3t4y26uLCLtiLLNP8bhZuZi24znFEdB+QnM2d0w4=")) {
            throw new RuntimeException("Ooops");
        }
    }
    public static void main(String[] args) throws Exception {
        test("SHA-2 224 bit", "SHA-224");
        test("SHA-2 256 bit", "SHA-256");
        test("SHA-2 384 bit", "SHA-384");
        test("SHA-2 512 bit", "SHA-512");
        test("SHA-3 224 bit", "SHA3-224"); // require Java 9+
        test("SHA-3 256 bit", "SHA3-256"); // require Java 9+
        test("SHA-3 384 bit", "SHA3-384"); // require Java 9+
        test("SHA-3 512 bit", "SHA3-512"); // require Java 9+
        test2();
    }
}
