1 /***
2 * Simple Web Spider - <http://simplewebspider.sourceforge.net/>
3 * Copyright (C) 2009 <berendona@users.sourceforge.net>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package simplespider.simplespider.dao.db4o;
20
21 import java.io.UnsupportedEncodingException;
22 import java.security.MessageDigest;
23 import java.security.NoSuchAlgorithmException;
24
25 public class MD5 {
26 private static String convertToHex(final byte[] data) {
27 final StringBuffer buf = new StringBuffer();
28 for (int i = 0; i < data.length; i++) {
29 int halfbyte = (data[i] >>> 4) & 0x0F;
30 int two_halfs = 0;
31 do {
32 if ((0 <= halfbyte) && (halfbyte <= 9)) {
33 buf.append((char) ('0' + halfbyte));
34 } else {
35 buf.append((char) ('a' + (halfbyte - 10)));
36 }
37 halfbyte = data[i] & 0x0F;
38 } while (two_halfs++ < 1);
39 }
40 return buf.toString();
41 }
42
43 public static String buildMD5(String text) {
44 try {
45 final MessageDigest md = MessageDigest.getInstance("MD5");
46
47 {
48 final byte[] bytes = text.getBytes("UTF-8");
49 text = null;
50 md.update(bytes, 0, bytes.length);
51 }
52 final byte[] md5hash = md.digest();
53 return convertToHex(md5hash);
54 } catch (final NoSuchAlgorithmException e) {
55
56 throw new RuntimeException("MD5 is missing", e);
57 } catch (final UnsupportedEncodingException e) {
58
59 throw new RuntimeException("UTF-8 is missing", e);
60 }
61 }
62
63 }