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