/*
 * [TestMD5.java]
 *
 * Summary: example use of MD5 with java.security.MessageDigest Test MD5 digest computation.
 *
 * 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 2004-06-07
 */
package com.mindprod.example;

import com.mindprod.common18.EIO;

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

import static java.lang.System.*;

/**
 * example use of MD5 with java.security.MessageDigest Test MD5 digest computation.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2004-06-07
 * @since 2004-06-07
 */
public final class TestMD5
    {
    /**
     * demonstrate how to compute an MD5 message digest requires Java 1.4+
     *
     * @param args not used
     *
     * @throws java.io.UnsupportedEncodingException   if UTF-8 not supported.
     * @throws java.security.NoSuchAlgorithmException if MD5 not supported.
     */
    public static void main( String[] args ) throws UnsupportedEncodingException, NoSuchAlgorithmException
        {
        final String s = "The quick brown fox jumped over the lazy dog's back; sample url: http://mindprod.com/jgloss/digest.html";
        final byte[] theTextToDigestAsBytes = s.getBytes( EIO.UTF8 );
        MessageDigest md = MessageDigest.getInstance( "MD5" );
        md.update( theTextToDigestAsBytes );
        // md.update( int ) processes only the low order 8-bits. It actually expects an unsigned byte.
        // result is 16 bytes, = 128 bits long.
        byte[] digest = md.digest();
        // will print MD5
        out.println( "Algorithm used: " + md.getAlgorithm() );
        // should be 16 bytes, 128 bits long
        out.println( "Digest is " + digest.length + " bytes long." );
        // dump out the hash
        out.print( "Digest: " );
        for ( byte b : digest )
            {
            // print byte as 2 hex digits with lead 0. Separate pairs of digits with space
            out.printf( "%02X ", b & 0xff );
            }
        out.println();
        }
    }