/*
 * [TestSHA.java]
 *
 * Summary: Example use of SHA-1 with java.security.MessageDigest. Demonstrate how to compute a SHA-1 message digest.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2009-01-01 initial version
 */
package com.mindprod.example;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Set;

import static java.lang.System.*;

/**
 * Example use of SHA-1 with java.security.MessageDigest. Demonstrate how to compute a SHA-1 message digest.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2009-01-01 initial version
 * @since 2009-01-01
 */
public final class TestSHA
    {
    /**
     * Compute SHA-1 digest
     *
     * @param args not used
     *
     * @throws java.io.UnsupportedEncodingException   if 8859_1 not supported.
     * @throws java.security.NoSuchAlgorithmException if SHA not supported.
     */
    public static void main( String[] args ) throws UnsupportedEncodingException, NoSuchAlgorithmException
        {
        final byte[] theTextToDigestAsBytes =
                "The quick brown fox jumped over the lazy dog's back"
                        .getBytes( "8859_1"/* encoding */ );
        // MessageDigest also supports MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512
        final MessageDigest md = MessageDigest.getInstance( "SHA" );
        md.update( theTextToDigestAsBytes );
        // md.update( int ) processes only the low order 8-bits. It actually expects an unsigned byte.
        final byte[] digest = md.digest();
        // will print SHA
        out.println( "Algorithm used: " + md.getAlgorithm() );
        // should be 20 bytes, 160 bits long
        out.println( "Digest is " + digest.length * 8 + " bits, " + digest.length + " bytes long." );
        // dump out the hash
        out.print( "Digest: " );
        for ( byte b : digest )
            {
            // print byte as 2 unsigned hex digits with lead 0. Separate pairs of digits with space
            out.printf( "%02X ", b & 0xff );
            }
        out.println();
        // Find out what other digests we can compute:
        final Set<String> algorithms = Security.getAlgorithms( "MessageDigest" );
        for ( String algorithm : algorithms )
            {
            out.println( algorithm );
            }
        }
    }