package de.duehl.basics.io;

/*
 * Copyright 2016 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

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

/**
 * Diese Klasse stellt aus Zeichenketten und Dateien einen MD5-Wert her.
 *
 * @version 1.01     2016-10-14
 * @author Christian Dühl
 */

public class MD5 {

    private MD5() {}

    public static String generateMd5FromFile(String fileName) {
        return generateMd5FromFile(fileName, Charset.UTF_8);
    }

    public static String generateMd5FromFile(String fileName, Charset charset) {
        Reader reader = new FineFileReader(fileName, charset);
        String contents = reader.readFileToString();
        reader.close();
        String md5 = generateMd5(contents, charset);
        return md5;
    }

    public static String generateMd5(String contents, Charset charset) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(contents.getBytes(charset.getCharsetAsString()));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public String md5Java(String message){
//        String digest = null;
//        try {
//            MessageDigest md = MessageDigest.getInstance("MD5");
//            byte[] hash = md.digest(message.getBytes("UTF-8"));
//
//            //converting byte array to Hexadecimal String
//           StringBuilder sb = new StringBuilder(2*hash.length);
//           for(byte b : hash){
//               sb.append(String.format("%02x", b&0xff));
//           }
//
//           digest = sb.toString();
//
//        } catch (UnsupportedEncodingException ex) {
//            ex.printStackTrace();
//        } catch (NoSuchAlgorithmException ex) {
//            ex.printStackTrace();
//        }
//        return digest;
//    }

    /* Quellen:
     * http://docs.oracle.com/javase/6/docs/api/java/security/MessageDigest.html#getInstance%28java.lang.String%29
     * http://stackoverflow.com/questions/415953/generate-md5-hash-in-java
     * http://javarevisited.blogspot.de/2013/03/generate-md5-hash-in-java-string-byte-array-example-tutorial.html
     * http://openbook.galileocomputing.de/java7/1507_22_005.html
     */

}
