001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2024, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014
015package ch.qos.logback.core.util;
016
017import java.math.BigInteger;
018import java.security.MessageDigest;
019import java.security.NoSuchAlgorithmException;
020import java.util.Arrays;
021
022public class MD5Util {
023
024
025    static String MD5_ALGORITHM_KEY = "MD5";
026    final MessageDigest md5;
027
028    public MD5Util() throws NoSuchAlgorithmException {
029        md5 = MessageDigest.getInstance(MD5_ALGORITHM_KEY);
030
031    }
032
033
034    public boolean equalsHash(byte[] b0, byte[] b1) {
035        return Arrays.equals(b0, b1);
036    }
037
038    /**
039     * Compute hash for input string. The hash is computed on the input alone
040     * with no previous or subsequent data.
041     *
042     * @param input
043     * @return
044     */
045    public byte[] md5Hash(String input) {
046        byte[] messageDigest = md5.digest(input.getBytes());
047        md5.reset();
048        return messageDigest;
049    }
050
051    public String asHexString(byte[] messageDigest) {
052        BigInteger number = new BigInteger(1, messageDigest);
053        StringBuilder hexString = new StringBuilder(number.toString(16));
054        // Pad with zeros if necessary
055        while (hexString.length() < 32) {
056            hexString.insert(0, '0');
057        }
058        return hexString.toString();
059    }
060
061}