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