KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freecs > util > HashUtils


1 /**
2  * Copyright (C) 2004 Jochen Schurich
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */

18 package freecs.util;
19
20 import java.security.MessageDigest JavaDoc;
21
22 import freecs.Server;
23
24 /**
25  * @author jocsch
26  *
27  */

28 public class HashUtils {
29     public static String JavaDoc encodeMD5(String JavaDoc source) throws Exception JavaDoc {
30         if (source != null) {
31             MessageDigest JavaDoc md = MessageDigest.getInstance("MD5");
32             md.update(source.getBytes(Server.srv.DEFAULT_CHARSET));
33
34             byte[] hash = md.digest();
35             // das byte[] in einen hexString, damit er mit der mySQL md5() Funktion 'kompatibel' wird
36
StringBuffer JavaDoc hexString = new StringBuffer JavaDoc();
37             for (int i = 0; i < hash.length; i++) {
38                 if ((0xff & hash[i]) < 0x10) {
39                     hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
40                 } else {
41                     hexString.append(Integer.toHexString(0xFF & hash[i]));
42                 }
43             }
44             return hexString.toString();
45         }
46         return null;
47     }
48 }
49
Popular Tags