1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2024, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  
15  package ch.qos.logback.core.util;
16  
17  import java.math.BigInteger;
18  import java.security.MessageDigest;
19  import java.security.NoSuchAlgorithmException;
20  import java.util.Arrays;
21  
22  public class MD5Util {
23  
24  
25      static String MD5_ALGORITHM_KEY = "MD5";
26      final MessageDigest md5;
27  
28      public MD5Util() throws NoSuchAlgorithmException {
29          md5 = MessageDigest.getInstance(MD5_ALGORITHM_KEY);
30  
31      }
32  
33  
34      public boolean equalsHash(byte[] b0, byte[] b1) {
35          return Arrays.equals(b0, b1);
36      }
37  
38      /**
39       * Compute hash for input string. The hash is computed on the input alone
40       * with no previous or subsequent data.
41       *
42       * @param input
43       * @return
44       */
45      public byte[] md5Hash(String input) {
46          byte[] messageDigest = md5.digest(input.getBytes());
47          md5.reset();
48          return messageDigest;
49      }
50  
51      public String asHexString(byte[] messageDigest) {
52          BigInteger number = new BigInteger(1, messageDigest);
53          StringBuilder hexString = new StringBuilder(number.toString(16));
54          // Pad with zeros if necessary
55          while (hexString.length() < 32) {
56              hexString.insert(0, '0');
57          }
58          return hexString.toString();
59      }
60  
61  }