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; 024import org.slf4j.Logger; 025import org.slf4j.LoggerFactory; 026 027/** 028 * Utility class for MD5 MD5 hash produces a 128-bit digest. 029 */ 030@InterfaceAudience.Public 031public class MD5Hash { 032 private static final Logger LOG = LoggerFactory.getLogger(MD5Hash.class); 033 034 /** 035 * Given a byte array, returns in MD5 hash as a hex string. 036 * @return SHA1 hash as a 32 character hex string. 037 */ 038 public static String getMD5AsHex(byte[] key) { 039 return getMD5AsHex(key, 0, key.length); 040 } 041 042 /** 043 * Given a byte array, returns its MD5 hash as a hex string. Only "length" number of bytes 044 * starting at "offset" within the byte array are used. 045 * @param key the key to hash (variable length byte array) 046 * @return MD5 hash as a 32 character hex string. 047 */ 048 public static String getMD5AsHex(byte[] key, int offset, int length) { 049 try { 050 MessageDigest md = MessageDigest.getInstance("MD5"); 051 md.update(key, offset, length); 052 byte[] digest = md.digest(); 053 return new String(Hex.encodeHex(digest)); 054 } catch (NoSuchAlgorithmException e) { 055 // this should never happen unless the JDK is messed up. 056 throw new RuntimeException("Error computing MD5 hash", e); 057 } 058 } 059}