1 /**
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 package org.apache.hadoop.hbase.util;
21
22 import java.security.MessageDigest;
23 import java.security.NoSuchAlgorithmException;
24
25 import org.apache.commons.codec.binary.Hex;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.apache.hadoop.hbase.classification.InterfaceAudience;
29 import org.apache.hadoop.hbase.classification.InterfaceStability;
30
31 /**
32 * Utility class for MD5
33 * MD5 hash produces a 128-bit digest.
34 */
35 @InterfaceAudience.Public
36 @InterfaceStability.Stable
37 public class MD5Hash {
38 private static final Log LOG = LogFactory.getLog(MD5Hash.class);
39
40 /**
41 * Given a byte array, returns in MD5 hash as a hex string.
42 * @param key
43 * @return SHA1 hash as a 32 character hex string.
44 */
45 public static String getMD5AsHex(byte[] key) {
46 return getMD5AsHex(key, 0, key.length);
47 }
48
49 /**
50 * Given a byte array, returns its MD5 hash as a hex string.
51 * Only "length" number of bytes starting at "offset" within the
52 * byte array are used.
53 *
54 * @param key the key to hash (variable length byte array)
55 * @param offset
56 * @param length
57 * @return MD5 hash as a 32 character hex string.
58 */
59 public static String getMD5AsHex(byte[] key, int offset, int length) {
60 try {
61 MessageDigest md = MessageDigest.getInstance("MD5");
62 md.update(key, offset, length);
63 byte[] digest = md.digest();
64 return new String(Hex.encodeHex(digest));
65 } catch (NoSuchAlgorithmException e) {
66 // this should never happen unless the JDK is messed up.
67 throw new RuntimeException("Error computing MD5 hash", e);
68 }
69 }
70 }