org.openml.apiconnector.algorithms.Hashing.java Source code

Java tutorial

Introduction

Here is the source code for org.openml.apiconnector.algorithms.Hashing.java

Source

/*
 *  OpenmlApiConnector - Java integration of the OpenML Web API
 *  Copyright (C) 2014 
 *  @author Jan N. van Rijn (j.n.van.rijn@liacs.leidenuniv.nl)
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package org.openml.apiconnector.algorithms;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.digest.DigestUtils;

public class Hashing {

    /**
     * Generates MD5 Hash of String
     * 
     * @param input - A string to be hashed.
     * @return MD5(input)
     * @throws NoSuchAlgorithmException
     */
    public static String md5(String input) throws NoSuchAlgorithmException {
        String result;
        MessageDigest md = MessageDigest.getInstance("MD5"); // or "SHA-1"
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        while (result.length() < 32) { // 40 for SHA-1
            result = "0" + result;
        }
        return result;
    }

    /**
     * Generates MD5 Hash of file content
     * 
     * @param input - A pointer to the file to be hashed.
     * @return MD5(input)
     * @throws IOException
     */
    public static String md5(File input) throws IOException {
        InputStream fis = new FileInputStream(input);
        return DigestUtils.md5Hex(fis);
    }
}