Throw any exceptions thrown unwrapped. This way, the caller knows what it's dealing...
[pithos] / src / gr / ebs / gss / server / webdav / MD5Encoder.java
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 package gr.ebs.gss.server.webdav;
18
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
34         // ----------------------------------------------------- Instance Variables
35
36
37         /**
38          * The possible hexadecimal characters.
39          */
40         private static final char[] hexadecimal =
41         {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
42                 'a', 'b', 'c', 'd', 'e', 'f'};
43
44
45         // --------------------------------------------------------- Public Methods
46
47
48         /**
49          * Encodes the 128 bit (16 bytes) MD5 into a 32 character String.
50          *
51          * @param binaryData Array containing the digest
52          * @return Encoded MD5, or null if encoding failed
53          */
54         public String encode( byte[] binaryData ) {
55
56                 if (binaryData.length != 16)
57                         return null;
58
59                 char[] buffer = new char[32];
60
61                 for (int i=0; i<16; i++) {
62                         int low = binaryData[i] & 0x0f;
63                         int high = (binaryData[i] & 0xf0) >> 4;
64                         buffer[i*2] = hexadecimal[high];
65                         buffer[i*2 + 1] = hexadecimal[low];
66                 }
67
68                 return new String(buffer);
69
70         }
71
72
73 }
74