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