KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > util > MD5Encoder


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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
18 package org.roller.util;
19
20
21 /**
22  * Encode an MD5 digest into a String.
23  * <p>
24  * The 128 bit MD5 hash is converted into a 32 character long String.
25  * Each character of the String is the hexadecimal representation of 4 bits
26  * of the digest.
27  *
28  * @author Remy Maucherat
29  * @version $Revision: 1.1 $ $Date: 2005/06/01 19:51:22 $
30  */

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

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

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

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