KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > catalina > util > MD5Encoder


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * 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
19 package org.apache.catalina.util;
20
21
22 /**
23  * Encode an MD5 digest into a String.
24  * <p>
25  * The 128 bit MD5 hash is converted into a 32 character long String.
26  * Each character of the String is the hexadecimal representation of 4 bits
27  * of the digest.
28  *
29  * @author Remy Maucherat
30  * @version $Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
31  */

32
33 public final class MD5Encoder {
34
35
36     // ----------------------------------------------------- Instance Variables
37

38
39     private static final char[] hexadecimal =
40     {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
41      'a', 'b', 'c', 'd', 'e', 'f'};
42
43
44     // --------------------------------------------------------- Public Methods
45

46
47     /**
48      * Encodes the 128 bit (16 bytes) MD5 into a 32 character String.
49      *
50      * @param binaryData Array containing the digest
51      * @return Encoded MD5, or null if encoding failed
52      */

53     public String JavaDoc encode( byte[] binaryData ) {
54
55         if (binaryData.length != 16)
56             return null;
57
58         char[] buffer = new char[32];
59
60         for (int i=0; i<16; i++) {
61             int low = (int) (binaryData[i] & 0x0f);
62             int high = (int) ((binaryData[i] & 0xf0) >> 4);
63             buffer[i*2] = hexadecimal[high];
64             buffer[i*2 + 1] = hexadecimal[low];
65         }
66
67         return new String JavaDoc(buffer);
68
69     }
70
71
72 }
73
74
Popular Tags