01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package org.apache.catalina.util;
19:
20: /**
21: * Encode an MD5 digest into a String.
22: * <p>
23: * The 128 bit MD5 hash is converted into a 32 character long String.
24: * Each character of the String is the hexadecimal representation of 4 bits
25: * of the digest.
26: *
27: * @author Remy Maucherat
28: * @version $Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
29: */
30:
31: public final class MD5Encoder {
32:
33: // ----------------------------------------------------- Instance Variables
34:
35: private static final char[] hexadecimal = { '0', '1', '2', '3',
36: '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
37:
38: // --------------------------------------------------------- Public Methods
39:
40: /**
41: * Encodes the 128 bit (16 bytes) MD5 into a 32 character String.
42: *
43: * @param binaryData Array containing the digest
44: * @return Encoded MD5, or null if encoding failed
45: */
46: public String encode(byte[] binaryData) {
47:
48: if (binaryData.length != 16)
49: return null;
50:
51: char[] buffer = new char[32];
52:
53: for (int i = 0; i < 16; i++) {
54: int low = (int) (binaryData[i] & 0x0f);
55: int high = (int) ((binaryData[i] & 0xf0) >> 4);
56: buffer[i * 2] = hexadecimal[high];
57: buffer[i * 2 + 1] = hexadecimal[low];
58: }
59:
60: return new String(buffer);
61:
62: }
63:
64: }
|