001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019
020package org.apache.hadoop.hbase.util;
021
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024
025import org.apache.commons.codec.binary.Hex;
026import org.apache.yetus.audience.InterfaceAudience;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030/**
031 * Utility class for MD5
032 * MD5 hash produces a 128-bit digest.
033 */
034@InterfaceAudience.Public
035public class MD5Hash {
036  private static final Logger LOG = LoggerFactory.getLogger(MD5Hash.class);
037
038  /**
039   * Given a byte array, returns in MD5 hash as a hex string.
040   * @param key
041   * @return SHA1 hash as a 32 character hex string.
042   */
043  public static String getMD5AsHex(byte[] key) {
044    return getMD5AsHex(key, 0, key.length);
045  }
046  
047  /**
048   * Given a byte array, returns its MD5 hash as a hex string.
049   * Only "length" number of bytes starting at "offset" within the
050   * byte array are used.
051   *
052   * @param key the key to hash (variable length byte array)
053   * @param offset
054   * @param length 
055   * @return MD5 hash as a 32 character hex string.
056   */
057  public static String getMD5AsHex(byte[] key, int offset, int length) {
058    try {
059      MessageDigest md = MessageDigest.getInstance("MD5");
060      md.update(key, offset, length);
061      byte[] digest = md.digest();
062      return new String(Hex.encodeHex(digest));
063    } catch (NoSuchAlgorithmException e) {
064      // this should never happen unless the JDK is messed up.
065      throw new RuntimeException("Error computing MD5 hash", e);
066    }
067  }
068}