package ru.yandex.wmtools.common.util;

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

/**
 * User: amima, baton
 * Date: 11.04.2007
 * Time: 16:45:08
 * To change this template use File | Settings | File Templates.
 */
public class Md5Util {
    private static MessageDigest getMessageDigest() {
        try {
            final MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            return algorithm;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getMd5(StringBuilder info) {
        return getMd5(info.toString());
    }

    public static String getMd5(String data) {
        MessageDigest digest = getMessageDigest();
        try {
            digest.update(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            digest.update(data.getBytes());
        }

        final BigInteger number = new BigInteger(1, digest.digest());
        return String.format("%032x", number);
    }
}
